C++: How to run program again?

Discussion in 'Mac Programming' started by Josh, Feb 27, 2006.

  1. macrumors 68000

    Josh

    Joined:
    Mar 4, 2004
    Location:
    State College, PA
    #1
    Hi,

    For my class, I needed to write program that asks a use for a number, then tells them whether or not that number is prime.

    It is supposed to run the program again and again until the user enters 0 as a number, then it exits.

    We never talked about running programs again, and I'm really not sure how to go about it. I *could* write a while(x=!0) loop, but that would require duplicative code, since the main loop would have to exist twice.

    So the only thing I can think of is to use a label, and a goto. But I have heard through my quick search on the net to avoid this method?

    What else would work?

    What I've got does work, but maybe there could be a better way.

    Here is my code (sorry if the formatting isn't good - just trying to get my idea down quickly):
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {	
    	cout << "Prime Number Tester" << endl;
    	cout << "-------------------" << endl;
    
    	Beginning: // label used to repeat program until 0 is entered
    
    	int x; // the number entered by the user
    	int y = 2; // variable used for loop to test if prime (y ranges from 2 to 1 less than x)
    	
    // ask user for a number
    
    	cout << "Please enter a number: ";
    	cin >> x;
    	cout << endl;
    
    // main loop. Once x = 0 (or less) program ends.
    
    	while(x>0)
    		{
    
    // divide X by all numbers 1-x to see if it is prime
    
    		while(y<=(x-1))
    			{				
    				if(x%y == 0)
    					{	cout << x << " is not Prime" << endl << endl;
    						break;
    					}
    	
    				y++;
    
    // if y makes it to x without being evenly divisble, x is prime.
    
    				if(y==x)
    					{	cout << x << " is Prime" <<  endl << endl;
    					}
    			}
    
    			goto Beginning;	
    		}
    
    	cout << "Thank you!" << endl;
    
    	return 0;
    }
    
     
  2. macrumors 6502

    Joined:
    Apr 16, 2003
    Location:
    Boston, MA
    #2
    Write a function that tests if a number is prime, and have it run from the main function, within a while loop.

    Or, you can nest loops, that would work - set x != 0 to start, and then move your first while loop to before the number is input.
     
  3. Guest

    caveman_uk

    Joined:
    Feb 17, 2003
    Location:
    Hitchin, Herts, UK
    #3
    Check out the 'do {} while(condition)' loop. It will probably be useful to you.
     
  4. macrumors 6502

    Joined:
    May 12, 2003
    #4
    I don't understand why you think it would require duplicate code. Can you come up with some psuedocode to illustrate what you mean? I personally think you are on the right track with that line of thinking, so let's examine that some more.
     
  5. thread starter macrumors 68000

    Josh

    Joined:
    Mar 4, 2004
    Location:
    State College, PA
    #5
    I can't recall a direct example - but I wrote a program once where I did this, and had to duplicate code to get it to loop. I wish I still had the code so I could post it, because I can't exactly remember my mode of thinking when I wrote it :/

    Are labels and 'goto' to be avoided? If not, then what I've got should be good, right?

    I think I will try the idea suggested in reply #1 and see how that goes.
     
  6. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #6
    dunno if they teach this anymore, but i find that using top-down programming is useful for avoiding such confusion. you can write your main() in very simple terms, making up function names for any complicated bits and putting off writing those functions until later. if you do it right, you'll end up with a well-organized, easily understood program with very small functions.

    my rule of thumb is that a function should never be so long that the whole thing doesn't fit on the page.

    here's an example of a top-down main:
    Code:
    int main(int argc, char** argv)
    {
        int possible_prime = 0;
    
        while (1)
        {
            get_user_input(possible_prime);
    
            if (possible_prime == 0)
                exit(0);
    
            check_possible_prime(possible_prime);
         }
    }
    
    this main should be self-explanatory. employing the same technique to get_user_input() and check_posssible_prime() [which obviously will also do the output to the screen] should make the thing a snap to write.
     
  7. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #7
    unless you're writing in assembler, yes.
     
  8. macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #8
    While you're working on that, check your logic. Your program won't return an answer for 1 or 2.
     
  9. thread starter macrumors 68000

    Josh

    Joined:
    Mar 4, 2004
    Location:
    State College, PA
    #9
    Ok, I've now got it working without labels or goto, using the do{}while() loop as suggested.

    (Thanks for pointing out the bug with 1 and 2 being entered! Definitely need to take a look at that)

    Here is my new code:
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {	int x =1; // the number entered by the user. defaulted to non-zero
    	
    	cout << "Prime Number Tester" << endl;
    	cout << "-------------------" << endl;
    
    // begin main loop
    	do{
    		int y = 2; // variable used for loop to test if prime (y ranges from 2 to 1 less than x)
    	
    // ask user for a number
    
    		cout << "Please enter a number: ";
    		cin >> x;
    		cout << endl;
    
    // divide x by all numbers 2 through (x-1) to see if it is prime
    		
    		if(x==0)
    			break;
    		while(y<=(x-1))
    			{				
    				if(x%y == 0)
    					{	cout << x << " is not Prime" << endl << endl;
    						break;
    					}
    	
    				y++;
    
    // if y makes it to x without being evenly divisble, x is prime.
    
    				if(y==x)
    					{	cout << x << " is Prime" <<  endl << endl;
    					}
    			}
    		}while(x=!0);
    
    	cout << "Thank you!" << endl;
    
    	return 0;
    }
     
  10. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #10
    it's also really inefficient. one need check the candidate prime against other primes, not every single number between 3 and the candidate.
     
  11. macrumors 6502

    Joined:
    May 12, 2003
    #11
    Josh -

    Yes, try to avoid gotos. It's considered bad style and code with even a few gotos becomes very difficult to read. No matter what you're trying to do, there's always a way to do it without gotos (and without duplicate code).

    While I was typing this, it looks like you solved it. Yeah, that looks better. As others have said, the code might need some work from a functional standpoint, but at least you got rid of the goto. :)
     
  12. Moderator emeritus

    Mitthrawnuruodo

    Joined:
    Mar 10, 2004
    Location:
    Bergen, Norway
    #12
    I used a for loop for the same problem...

    Java code (but should be very easy to "translate" (;))):

    Code:
    /*
    	isPrime, version 1.0
    	by Mitthrawnuruodo
    */
    
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.lang.*; 
    
    class isPrime {
        public static void main ( String[] args ) {
    	// System.out.println(args.length);
    	if (args.length < 1) {
    		System.out.println("You must at least provide one number to check!");
    	} else {
    		for (int j = 0; j < args.length; j++){
    			int a = (Integer.valueOf(args[j])).intValue();
    			if (a < 4){
    				System.out.println("" + a + " is too low, cannot be bothered to check something under 3");
    			} else {
    				boolean er = true;
    				[B]for (int i = 2; i<=a/i; i++)[/B]{
    					if (a%i == 0) { 
    						System.out.println("" + a + " = " +  i + " * " + a/i + "; and thus NOT a prime");
    						er = false;
    						break; // Break if you don't need to find any more common denominators.
    					}//if
    				}//for
    				if (er) System.out.println("" + a + " is a prime, I think... =)");
    			}//else(a<4)
    		}//for j=0->args.length	
    	}//else(args<1)	
        }//main
    }//class
     
  13. Guest

    caveman_uk

    Joined:
    Feb 17, 2003
    Location:
    Hitchin, Herts, UK
    #13
    Your do while line should have '!=' not '=!'.

    Also I'd reverse the logic of the if (x==0) break line. If you do 'if (x!=0) { dosomestuff }' you won't need the 'break' at all.
     
  14. thread starter macrumors 68000

    Josh

    Joined:
    Mar 4, 2004
    Location:
    State College, PA
    #14
    Very true. However, that would require either including a known list of primes, or first creating a list of primes.

    Were just getting into loops and "i++" and I think the point of this lesson is to do what it is doing (albeit ineffecient) so that we could a get good understanding of this.

    At this stage in the class, if I turned in something beyond what we've learned so far, I'd probably lose more credit than I'd gain :(

    Fixed. Thanks for pointing that out! I appreciate all the help.
     
  15. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #15
    it's beyond the scope of your assignment, i agree, but i can see how it can be an elegant solution. since the user is testing a series of candidates, you have the opportunity to not re-do work for each candidate.

    instead of incrementing by one or two, you could generate a list of primes up to the candidate and save them off, also making a note of the largest prime you've got so far.

    when a new candidate is entered, check it against the largest prime. if it's smaller, you've then already got a list of test primes. if it's larger, you can use the test primes you've got, then generate and store off the new ones as needed.

    doing so would help alleviate the issue that, the larger the number the user entered, the longer it would take to check that number.
     
  16. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #16
    josh, i am curious about this class and other programming courses you've taken:

    1. do they still teach top-down and bottom-up programming?
    2. are they teaching OO concepts alongside C++?
    3. what is the course title/description?

    thanks. just curious. i did my computer science degree in the mid to late 80's.
     
  17. thread starter macrumors 68000

    Josh

    Joined:
    Mar 4, 2004
    Location:
    State College, PA
    #17
    This is the first programming class I've taken, so I'm not familiar with top-down/bottom-up programming. I've never heard that term before.

    I looked it up on the net, and it does seem like an important concept. Might have to be something I read up on my own - I don't think my current course will mention this (actually, I don't think my current course will mention a lot of what I'd like it to).

    So far, we have not even discussed object-oriented material, or even functions. I read our book well beyond were we are now, so I personally have an understanding of OO and using functions. Judging from the pace of this class and where it seems to be going, I also doubt this will be covered.

    Here is the course info:
    This is week 7 of the class, and we are just now touching on loops and incrementing. Even though I'm new to programming, I wish the pace was a little quicker and things were more in-depth.
     
  18. macrumors 601

    zimv20

    Joined:
    Jul 18, 2002
    Location:
    chicago
    #18
    that does seem pretty slow. as my friend Tony used to say about teaching a C class: "they're teaching it wrong! it should be: day 1. pointers!"

    thanks for the class description. i don't see much OO in there, but i'm torn about that.

    generally, i think that OO should be taught alongside C++. it doesn't make much sense to use C++ for procedural programming, imo. going with that, the only option is teach another language first, like C. but i have trouble seeing a university doing that these days.

    in fact, it now makes me question whether procedural needs to be taught at all. hm.

    .......

    definitely see if you can employ some top-down techniques in your coding. i think it will greatly help you organize, which becomes of paramount importance once your programs go beyond 100 lines or so. some projects have millions of lines of code and the only hope for that kind of project succeeding is through diligent use of good coding practices.
     

Share This Page