garc2541

My assignment asked me to write a function that would print out a "*" when a number was prime. My output also has print out the odd numbers between 5 and 49. Anyway My function prints out only the prime number, while I want it to print out all the numbers and then just have a "*" next to a prime number. The function is at the bottom and in bold. Also if its prime it must return 1 otherwise return 0.
Thank You for any hints and help.

``````#include <iostream>
using namespace std;

int sumsq(int);
int sumcb(int);
int prime(int);

int main()
{
cout<<" Number SumSq   SumCb   PRIME "<<endl;
cout<<endl;

int numb;
int sum;
int sum1;

for(numb=5;numb<=49;numb+=2)
if(prime(numb)==1)

cout<<numb<<"       "<<sumsq(numb)<<"      "<<sumcb(numb)<<endl;

sum=sumsq(numb);
sum1=sumcb(numb);

system ("pause");
return 0;
}

int sumsq(int numb){
int yoyo;
int sum =0;

for(yoyo=1;yoyo<=numb;yoyo++)
sum+=yoyo*yoyo;
return sum;
}

int sumcb(int numb){
int val;
int sum1 = 0;

for(val=1;val<=numb;val++)
sum1+=val*val*val;
return sum1;
}

[B]int prime(int numb) {
int p;

for (p=2; p<=numb/2; p++) {
if (numb%p==0) {
return 0;
}
}
cout << "*" << endl;
return 1;[/B]}``````

vmanes 1,165

A better design is to have the prime( ) function only return the 0 or 1 indicating primeness. Let main( ) be responsible for the actual printing of the number and * if appropriate.

Your for loop is only printing the values that are prime. A little modification will fix that:

``````for( numb = 5; numb <= 49; numb += 2 )
{
if( prime(numb) ==1 )
cout << "*   ";

cout << numb << "       " << sumsq( numb ) << "      " << sumcb( numb ) << endl;
}``````

If you work on using a more consistent indenting style, the fact that the cout line was the action of the if condition would be more apparent, and then you'd see why you were only printing the primes. Don't be afraid to use { } to show blocks, even when not strictly needed. And put some blanks between operands and operators. It does aid readability.

Val

garc2541

i keep getting an error message saying prime cannot be used as a function even after i intialized it.

garc2541

so the function would contain an if and else statment?

vmanes 1,165

Double check all your { } pairs, make sure you've not left an open set in main( ). That could lead the compiler to thinking you're trying to declare a function inside a function.

Also, it helps if you post the exact message.

Your prime function should be just as you originally posted, with the cout << line removed. An else is not needed.

WaltP 2,905

Double check all your { } pairs, make sure you've not left an open set in main( ). That could lead the compiler to thinking you're trying to declare a function inside a function.

The easiest way to do this is to learn how to format your code correctly.