• C

Newbie Blues...

I have been trying to get a program together that prompts user to enter a min and max number...  it then determines the primes between the min and max numbers...

I got help here with the prime part but I am having trouble trying to determine if the min number is > 1 and the max num is > than the min number before it loops through the prime determining iteration...

I am learning from a book and I must be missing something or not putting enough time into coding to make it sink in... here is what I have so far:

#include <stdio.h>
#include <stdlib.h>


int main()
{

      int min_num;                        
      int max_num;                        
      int num;                              
      int prime;                              
      int i;      
      int j;                              

      printf("Enter two numbers greater than 0 - seperated by a space: ");
      while ((num = scanf("%i %i", &min_num, &max_num)) == 2)
      {
      if(min_num > 1 && min_num < max_num);
      for(i=min_num; i<=max_num; ++i)
      {   prime=1;   /* assert i is prime */
      for(j=2; j<=i/2; ++j)
                  {
      if(i%j==0)prime=0;                   

                  }
                              if(prime)printf("%d is prime\n",i);
            }
      else printf("You must enter a minimum number > 1 and less than the max number!");
      }
      if (num != EOF)
      printf("Warning: Encountered error in reading input. \n");

      return EXIT_SUCCESS;                  
}

Would it be best to creat a function to compute the primes? Also, I am having trouble when errors are encountered of getting the program to kick back to the scanf prompt asking for input...

Thanks,

mapper
mapperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mapperAuthor Commented:
Edited text of question.
0
imladrisCommented:
The if statement:

if(min_num > 1 && min_num < max_num);


as shown above is non-functional. No action is taken on the outcome of the condition, since the "body" associated with the if statement is a null statement. You probably want to go:

if(min_num > 1 && min_num < max_num)
{  for(i=min_num; i<=max_num; ++i)
   {  ...
      ...
   }
}
else printf("You must enter...

Or was the semi-colon just a typo? I actually wouldn't expect the above code to compile. The last else I show is dangling in your code.


What is happening with errors? It appears to loop nicely getting pairs of numbers, and exiting when it doesn't.


0
mapperAuthor Commented:
Okay, let me look at the code and integrate your suggestion.  I was probably not explicit enough with my comments to be understandable.  What I am trying to do is develop the code that asks a user (scanf) to enter a min and max number.  The code takes the two variables and determines if they are a valid range (Min > 1 and max > min) then loops through the set and then printf all the primes and then prints a total number of times - the != eof error was easy enough - that was explained nicely in the book I am reading - but, my concerns are - how do I kick back out if the user enters a -1 for example or the two variables 55 2 (where the min value is greater than the max value)?  Also, I want the user to be able to enter two more variables when the primes have been determined and then printf'ed to the sceen?

Thanks,

mapper
0
Increase Security & Decrease Risk with NSPM Tools

Analyst firm, Enterprise Management Associates (EMA) reveals significant benefits to enterprises when using Network Security Policy Management (NSPM) solutions, while organizations without, experienced issues including non standard security policies and failed cloud migrations

curriCommented:
I usually do either of 2 things:

1. Check the condition, and if false, exit.

this would be something like:      
   if(!(min>1 && max>min))
      return 0;  
or, using DeMorgan's law
   if(min<1 || max<=min)
      return 0;

2. Make a loop and keep asking the user until it gives you valid values. In pseudocode:

      scanf ....
      while ( invalid values)      {
            //tell the user
            puts( ...)
            // ask again
            scanf ....
      }

BTW, I would also recomend making a function is_prime that would tell you if a number is a prime.

curri
0
imladrisCommented:
curri suggestions are the standard kinds of means for dealing with such things.

However it appears to me that your code will work as well (if the if statement gets fixed). It gets the two values:

while ((num = scanf("%i %i", &min_num, &max_num)) == 2)
{

checks them:

if(min_num > 1 && min_num < max_num)
{

and if the condition is false it goes to the else:

else printf("You must enter a minimum number > 1 and less than the max number!");

after which it goes to the top of the loop.

Am I reading it wrong? What actually happens if you enter 55 2?
0
mapperAuthor Commented:
imladris,

If you enter 55 2 - nothing happens - so it is not entering into the loop (as designed) but here is where I was trying to explain previously - the code works great - its just that I can not figure out how to implement the buzzers I want to add on.  

If max entered before min - error message and allow user to enter the min then the max.

If < 1 value entered - error message - min value must be greater than 1 and allows user to enter the two values again.

Thanks,

mapper
0
imladrisCommented:
That is exceedingly perplexing. The scanf has no basis for behaving differently based on the input values. Have you verified that it doesn't enter the loop, or are you simply basing this on the observation that nothing happens (for which there may be other explanations).

If the latter, please verify whether it is entering the loop by adding a printf after the while, something like:

while ((num = scanf("%i %i", &min_num, &max_num)) == 2)
{ printf("Now in loop\n");
if(min_num > 1 && min_num < max_num);

See if the debug line prints (or go through it with a debugger).
It may be that the error message simply isn't getting pushed to the console (maybe add a newline to the end of the string e.g.:

else printf("You must enter a minimum number > 1 and less than the max number!\n");

Sometimes things don't get flushed without that.
0
mapperAuthor Commented:
imladris,

You were right!  I added the printf and then entered 55 2 again
and I got the print statement - but nothing happened after that. I guess it's doing what it is suppose to do, but I have to cntl Z to get the program to terminate - is there any way to have the promt to enter another set of numbers and loop through the program again?

I am sorry about that - we are working on one thing and I am running down another road again...

Sorry, please excuse that last plea...

I appreciate the help you are giving me now...

Thanks,

Mapper
0
mapperAuthor Commented:
imladris,

I was able to add an else statement - to test if the numbers entered did not match the parameters for validation (min > 1 and < min) but now I get the following when I execute the program:

Enter two numbers greater than 0 - seperated by a space: 55 2
Please enter a min number > 1 and smaller than the second number.
Warning: Encountered error in reading input.
Press any key to continue

I am  not getting the eof warning that I have and I wanted the

Enter two numbers greater than 0 - seperated by a space:

printf statement that starts the program to come up again to give the user the chance to enter valid numbers.

Thanks,

mapper
0
mapperAuthor Commented:
imladris,

I am sorry that last comment should have read;

I am now getting the eof error message too (Warning: Encountered error in reading input. ) ...

thanks,

mapper
0
mapperAuthor Commented:
imladris,

I must have goofed up something (go figure) now no matte what numbers I enter I get the warning...

#include <stdio.h>
#include <stdlib.h>


int main()
{

int min_num;                              
int max_num;                        
int num;      
int prime;      
int i;            
int j;            

printf("Enter two numbers greater than 0 - seperated by a space: ");
while ((num = scanf("%i %i", &min_num, &max_num)) == 2)
{
if(min_num > 1 && min_num < max_num)
for(i=min_num; i<=max_num; ++i)
{   prime=1;    
      for(j=2; j<=i/2; ++j)
      {
            if(i%j==0)prime=0;                   
      }
      if(prime)printf("%d is prime\n",i);
}
else
printf("Please enter a min number > 1 and smaller than the second number. \n");
break;
}
      
if (num != EOF)
printf("Warning: Encountered error in reading input. \n");

return EXIT_SUCCESS;                
}

What have I screwed UP??

Thanks,

mapper
0
mapperAuthor Commented:
imladris,

I had to rem out the

if(min_num > 1 && min_num < max_num)  statement to get the program to work again...

now that I have rem'ed out that statement I am back to the original code that worked.  However, I do not have the fail safe check to ensure the numbers entered are valid (min > 1 and < max)...

Thanks,

mapper
0
szetoaCommented:
Mapper,

  Actually your program works except with the misplacement of the "break".  If I understand the purpose of your "break" is that you want to break out of the loop only if the user enters two valid number and you done with finding the prime numbers.  You should put it inside the if (min_num > 1 && min_num < max_num) block.  Otherwise, it will break out of the loop if the user enters invalid numbers.

  Also you will get the warning message every time your program exits the while loop because your num variable contains the number of matching items in the scanf().  It will be a number greater or equal to 0 and will never be equal to EOF, whatever EOF is defined to.

  One more thought.  If your user enters 1 and 7 or 3 and 3, your if (min_num ...) statement will be false because min_num is not greater than 1, it's equal to 1.  Or in the second case, min_num is not less than max_num.  But these two cases are both valid.  You can change it to:

  if ( min_num >= 1 && min_num <= max_num )

  I have modified your code a little bit.  Hope this helps clear up your confusion.

=============================
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int    min_num;
  int    max_num;
  int    num;
  int    prime;
  int    i;
  int    j;

  printf( "Enter two numbers greater than 0 - seperated by a space: " );

  while (( num = scanf( "%i %i", & min_num, & max_num )) == 2 )
  {
    if ( min_num >= 1 && min_num <= max_num )
    {
      for ( i = min_num; i <= max_num; ++i )
      {
        prime = 1;

        for ( j = 2; j <= i / 2; ++j )
          if ( i % j == 0 )
            prime = 0;

        if ( prime )
          printf( "%d is prime\n", i );
      }
    }
    else
      printf( "Please enter a number > 1 and smaller than the second number. \n" );
  }

  if ( num != 2 )
    printf( "Warning: Encountered error in reading input. \n" );

  return EXIT_SUCCESS;
}
0
mapperAuthor Commented:
imladris,

Thanks!  I will play around with it and see if I can keep from screwing it up! :-)

I have been playing with having the total number of primes found and got that working - but was having trouble with the printf statement asking for two more numbers...  I was re-reading about assignment operators (while (( num = scanf( "%i %i", & min_num, & max_num )) == 2 ) and trying to add a printf statement at the end of the while block asking for the two new numbers - but, this new code you have provided is going to be too much to chew on for my mind (at this beginning stage of C) to fathom all at once...  I will try to get the code working and then add the count (number of primes found) and then adding the printf statement to provide the user the chance to input two more variables...

I really appreciate your help...

But, please let me digest and then try to implement it...

Thanks,

Mapper

BTW: What part of BC do you live in?  I noticed from your profile you are from the Great White North - HNIC rules...

so does grapes...

:-)
0
mapperAuthor Commented:
Sorry szetoa,

I didn't even look to see who had sent the comment...

My head is so cloudy from trying to digest all of this...  I am very slow to learn but when I do - I tend to keep it...

Thanks,

mapper
0
imladrisCommented:
Agreed. Removeing the break, will allow the code to go back to the top of the loop and get another pair of numbers.

And yes, getting out in this context is not straightforward. A call to scanf will simply patiently wait for the console to produce input. There is no EOF, since it will keep on expecting the user to enter something. You would get an EOF nicely if you were reading from a file, but that is another story.

Usually, the simple tactic is to exit based on a "magic" value like 0:

while ((num = scanf("%i %i", &min_num, &max_num)) == 2)
{ if(min_num==0)break;
  if(min_num > 1 && min_num < max_num)

And, yes, the comparison of the scanf result to 2 in the while statement probably less than useful. The input console is a special case of a file in the C environment.

0
imladrisCommented:
I live in Surrey, work in Vancouver.
0
mapperAuthor Commented:
imladris,

I was using the eof because the book I am reading uses it in all of the examples I have read so far - not matter what the input they are looking for - that's why I added the != eof ...

Funny thing - I just entered three numbers and the program executed just fine...  Sheez, now I am totally confused...  which is about a quarter of an inch to the left of where I was previoulsy...

I need to play with the code I have and then see what the code is telling me - I am not too

BTW: I changed the eof to:

if (num != 2)
printf("Warning: Encountered error in reading input. \n");

and tried to enter 3 numbers - it worked just fine...

I am totally lost now...

Thanks,

Mapper

BTW: I live in the Seattle area...
0
imladrisCommented:
Again, scanf is not a comprehensive input function. All these C things come from a Unix background that considers everything to be a file. The input console is just a special case. So if you enter three values, it takes the first, and carries on (two is what you asked for), the third would come up in the next scanf.

Any serious interactive input has to be handled very differently.

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mapperAuthor Commented:
imladris,

Okay - I think I am starting to get with what you and the other folks have been saying.

Here is what I ended up with - it seems to work just fine except for more than two numbers entered...

#include <stdio.h>
#include <stdlib.h>

int main()
{
int min_num;                              
int max_num;                              
int num;                                    
int prime;                                    
int i;                                    
int j;      
int count;       

count = 0;      

printf( "Enter two numbers greater than 0 - seperated by a space: ");

while ((num = scanf("%i %i", & min_num, & max_num)) == 2)
{ if(min_num==0)break;
if (min_num >= 1 && min_num <= max_num)
{
for (i = min_num; i <= max_num; ++i)
{
prime = 1;            

for (j = 2; j <= i / 2; ++j)
if (i % j == 0)       
prime = 0;

if (prime)
printf("%d is prime\n", i);
count = count + prime;
}
printf("The number of primes found is %i.\n", count);
printf("Enter two more numbers, or Control + Z to quit! \n");
count = 0;
}
else
printf("Please enter a whole number > 0 and smaller than the second  whole number. \n");
}

if (num != 2)
printf("Warning: Encountered error in reading input. \n");

return EXIT_SUCCESS;
}

The only problem (beside the extra numbers being entered) is that when zero is entered it gives you the press any key to continue (press a key dos window closes)...

Any thoughts on that?

Thanks,

Mapper
0
ozoCommented:
1 is not prime.
0
mapperAuthor Commented:
imladris,

Ozo - is absolutely right technically speaking a prime number is "An integer greater than
one is prime if its only positive divisors are itself and one (otherwise it is composite)" so the program lists one as a prime but it is not...

How would I append the code?

Thanks,

Mapper
0
imladrisCommented:
To avoid listing 1 as a prime I would force min_num to be > 1. You can either do that explicitly (i.e. only accept numbers greater than one, in the same way you now only accept numbers greater than 0) or:

while ((num = scanf("%i %i", & min_num, & max_num)) == 2)
{ if(min_num==0)break;
  if(min_num==1)min_num=2;
if (min_num >= 1 && min_num <= max_num)

The press any key to continue before the window closes is an operating system artifact. Windows, for instance, can be configured to close on exit.
0
mapperAuthor Commented:
imladris,

Thanks - would it be possible to determine a percentage of primes by taking a count of the primes and dividing that by the total number?  

Thanks again,

mapper
0
imladrisCommented:
Sure. Add a counter that increments everytime you find a prime. Then divide by max_num-min_num at the end and list the result.
0
mapperAuthor Commented:
imladris...

Thanks a bunch - I think that I have learned a lot from this exercise - I will play around with this and read what I have read again - then try something else...  My kids are into pokemon and maybe will do some type of searchable program where they can add the information and then search for it...

I don't know but I need to learn about  arrays - and file i/o those are the next sections I need to start digesting...

Thanks again,

mapper
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.