1 Replies - 4242 Views - Last Post: 23 February 2009 - 09:40 PM Rate Topic: -----

#1 queue2008  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 8
  • Joined: 05-February 09

How to show output of For loop in Desending order

Post icon  Posted 23 February 2009 - 09:14 PM

Hi again

I have this exercise which states :

Write a program (lab5_12.cpp) that calculates all prime numbers between 1 and an integer
entered by the user and outputs them on the screen. A prime number is a positive integer that
has no other factors other than itself and 1. You should use a nested loop, i.e., write code
where a for loop runs within another for loop.
The program should print prime numbers in reverse order, i.e., starting with the largest one.
Once you have written your code, test it with the following input:
a. 10
b. 15
c. 20
If you are having problems with this task, start by writing a for loop to check if a number is
prime or not. Once this is complete, nest this loop within another loop to check all numbers in
the range given by the user.

I have been able to find the prime numbers , but the problem is how i can show the output of prime numbers from largest to smallest. this is my code :

#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>

using namespace std;

int main ()

{
  int n , prime;
  cout<<"Enter an integer number to calculate all the prime numbers  :";
  cin>>n;
  for( int i = 2; i <= n; i++)
  {
	 prime  = 1;
	 for( int j = 2; j <= i; j++)
	 {
		if( i == j)
		   continue;
		else if( i % j == 0)
		prime = 0;
	 }
	 if(prime)
	 
	   {
	 cout << i << " " <<endl;
	   }	   
	
  }

  return 0;
  }	


Is This A Good Question/Topic? 0
  • +

Replies To: How to show output of For loop in Desending order

#2 bsaunders  Icon User is offline

  • D.I.C Addict

Reputation: 44
  • View blog
  • Posts: 571
  • Joined: 18-January 09

Re: How to show output of For loop in Desending order

Posted 23 February 2009 - 09:40 PM

I think the best way to print the prime numbers from largest to smallest is to check if a number is prime starting with the number entered by the user and ending with 2.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1