cannot achieve desired output (cout) from a C++ loop - c++

thanks to your help last night I was able to get my program computing my input properly, but now I am have trouble formatting my output properly. This is the problem:
My program should only print "is prime" on lines with prime numbers. But it prints on ever line like this:
http://oi42.tinypic.com/30igbvq.jpg
I cannot for the life of me figure out why it is doing this, all of my functions should work.
Stack I need your help again!
#include <iostream>
using namespace std;
void primecheck(int x); // proto
void countr(int rnm, int lnm); // proto
void prime(int x) // this function finds the prime factors of a number.
{
int lastr = 2;
int count = 0;
while (lastr < x)
{
if (x % lastr == 0)
{
cout << x << " " << lastr << "*";
x /= lastr;
}
else
++lastr;
}
primecheck(x); // calls to check if number is prime, "Is prime"
}
void console(int rnum, int lnum) // this prompts the user for two numbers then stores the answers
{
cout << "please enter two numbers ";
cin >> rnum;
cin >> lnum;
countr(rnum, lnum);
}
void countr(int rnm, int lnm) // this function loops the prime function until all the numbers are computed
{
int i = rnm;
do{
prime(i);
i++;
} while (i <= lnm);
return;
}
int main() // main, calls console then pauses when finished
{
int e = 0;
int r = 0;
console(e, r);
system("PAUSE");
}
void primecheck(int x) // checks to see if then number is prime. if counter is equal to 2 than number is prime.
{
int counting = 0;
for (int a = 1; a <= x; a++)
{
if (x %a == 0)
{
counting++;
}
}
if (counting == 2)
{
cout << x << " is prime " << endl;
}
else
{
cout << x << endl;
}
}

You're using a /= operator in prime(). That's an assignment operator and is modifying the value of x, making x always prime whenever primecheck() is called.

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;
}

display all the Prime numbers which are less than certain number

I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
if (isPrime(Num))
{
cout << " is a Prime number." << endl;
}
else
cout << " is not a Prime number." << endl;
return 0;
}
//isPrime
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else if
for(int n = 2; n < 200; n++) { // HERE
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if(isPrime == true)
cout<<n<<" ";
}
return 0;
else
return false;
}
}
}
return false;
}
You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
// Check numbers here
for(int n = 2; n < 200; n++) {
if (isPrime(n)){
cout << n << " is a Prime number." << endl;
}
}
return 0;
}
//isPrime - This is your original isPrime Code
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else
return false;
}
}
}
return false;
}

write program to display odd and even numbers

im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}

Prime-testing program not working

#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 1;
int i = 0;
while (i == 0 && y < sqrtf(x))
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
if (i == 1)
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
}
return 0;
}
This is a code I created to test for primes. After sorting out several debugging issues I was able to run it.
It opened the command window, read 'Enter a number' and closed itself the second I entered a number.
Help?
You have to:
close the while loop in the correct place
change the if (i == 1) condition (i==1 means x is divisible by some y)
start with y = 2 (every number is divisible by one)
include sqrtf(x) in the loop (y <= sqrtf(x) or 15, 25, 35... are primes).
So:
int main()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 2; // <-- changed
int i = 0;
while (i == 0 && y <= sqrtf(x)) // <-- changed
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
} // <-- moved here
if (i == 0) // <-- changed
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
return 0;
}
works (more or less...).
Anyway:
don't use using namespace std; (Why is "using namespace std" considered bad practice?)
\n should be your default ("\n" or '\n' or std::endl to std::cout?)
y and x are integers so you can use % instead of fmodf
avoid premature pessimization: prefer preincrement, only use postincrement if you're going to use the original value
else { i = 0; } is superfluous
you can change y < sqrtf(x) with y * y <= x (and you don't need math.h anymore) or find square root of number then start the loop
Somewhat better (but far from perfect):
#include <cmath>
#include <iostream>
int main()
{
int x;
std::cout << "Enter a number.\n";
std::cin >> x;
int square_root = std::sqrt(x);
int y = 2;
int i = 0;
while (i == 0 && y <= square_root)
{
if (x % y == 0)
i = 1;
++y;
}
if (i == 0)
std::cout << "Your number is prime.\n";
else
std::cout << "Your number is composite.\n";
return 0;
}
Now:
input validation, i.e. check for bad input values (How to check if input is numeric in C++)
special cases checking (is the number one a prime number?)
a bool would express your intentions better than int i;
improve the algorithm (Determining if a number is prime, Which is the fastest algorithm to find prime numbers?, Primality tests)

Need to fix a simple loop

Okay I need to write a function that takes an integer parameter and prints the sum of each number up to that point. For example, n = 10 would be 1+2+3+4+5+6+7+8+9+10.
int SumOneToN(int n)
{
int x = 0;
while (x <= n)
{
cout << x+(x+1) << " ";
x++;
}
cout << endl;
}
So what's going on here?
1. Set up the function as SumOneToN.
2. Initialize x to 0.
3. Create a while loop that states while x is less than our parameter, we take x, add it to x+1 (so that we get our current x value added to the next one), print it, then we add to x for the loop to go again until we meet the parameter.
That's how I thought it should work, anyways. What actually returns is:
1 3 5 7.. etc
I'm not sure where I went wrong?
Try this :
int SumOneToN(int n)
{
int x = 1, sum=0;
while (x <= n)
{
sum=sum+x;
cout << sum << " ";
x++;
}
cout << endl;
return sum;
}
Why not use some maths an not have the loop in the first place?
i.e.
int SumToOne(int n) {
return (n * (n + 1))/2;
}
int SumOneToN(int n)
{
int sum=0;
for(int x=1;x<=n;x++)
{
sum+=x;
cout << sum << " ";
}
cout << endl;
return sum;
}
Write the "+" sign in the inverted commas and cout x; once before the while loop. If you want to do it by SUM than you have to introduce another variable and the above solutions are fair enough.
#include <iostream>
using namespace std;
int SumOneToN(int n)
{
int x = 1;
cout << x ;
x++;
while (x <= n)
{
cout << " + " << x ;
x++;
}
cout << endl;
}
int main()
{
int x;
cin >>x;
SumOneToN(x);
return 0;
}
You can try this:
int SumOneToN(int n){
int sum=n,x=1;
while(x<n){
cout<<x<<"+";
sum+=x;
x++;
}
cout<<x;
return sum;
}
Note: This wont print an additional '+' after last number.
Hey you are using same variable for Sum & as looping variable
try this code
int add(int n)
{
int sum=0;
for(int i=1;i<=10;i++)
sum=sum+i;
return sum;
}