Thread: Displaying prime numbers using nested loops?

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    8

    Question Displaying prime numbers using nested loops?

    So I have a programming assignment in which I'm asked to display all of the prime numbers between 1 and 100 using nested loops. And I'm also asked to display the quantity of numbers that are primes between 1 and 100.

    So here is the code I wrote that addresses the first part, but I didn't get to the second requirement yet.

    Code:
    	int x = 1;
    	int loop2 = 2; 
    
    	while (loop2<100){
    
    		loop2++;
    		x++;
    
    		while (x < loop2){
    
    			if ((loop2 % x != 0) && (loop2 < 100)){
    				std::cout << loop2 << std::endl;
    			}
    			else if (loop2 % x == 0){
    
    			}
    			else{
    
    			}
    		}
    		
    	}
    I haven't placed any statements in the else-if or else brackets because I don't need to do anything if they evaluate to be true.

    So when I compile and run this, I see an endless repeating string of 3's in the output of the console. So I'm obviously doing something very wrong, and it has to do with my logic, but I can't figure out what exactly is wrong with my logic.

    If someone could point me in the right direction with regards to what is wrong with my logic, I would really appreciate it!

  2. #2
    Guest
    Guest
    Code:
            int x = 1;
    	int loop2 = 2; 
    
    	while (loop2<100){ // 2 < 100 is true, proceed
    
    		loop2++; // loop2 = 3
    		x++; // x = 2
    
    		while (x < loop2){ // 2 < 3 is true, proceed
    
    			if ((loop2 % x != 0) && (loop2 < 100)){ // (3 % 2 != 0) is true && (3 < 100) us true, proceed
    				std::cout << loop2 << std::endl; // print 3
    			}
    			else if (loop2 % x == 0){
    
    			}
    			else{
    
    			}
    		} // end of loop body, return to top, (2 < 3) still true, rinse, repeat...
    		
    	}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with finding only prime numbers with for loops
    By AlmondSeason in forum C++ Programming
    Replies: 11
    Last Post: 02-19-2013, 12:51 AM
  2. Replies: 1
    Last Post: 03-16-2012, 02:07 AM
  3. Displaying a table using nested loops
    By leviterande in forum C Programming
    Replies: 13
    Last Post: 09-29-2009, 04:42 PM
  4. displaying characters per line and checking prime numbers
    By xclarkiex5x in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2007, 12:28 AM

Tags for this Thread