3 Replies - 6861 Views - Last Post: 20 February 2009 - 09:32 AM Rate Topic: -----

#1 yvsham  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 20-February 09

how to print N numbers in descending order

Post icon  Posted 20 February 2009 - 08:43 AM

:wub:

Attached File(s)


Is This A Good Question/Topic? 0
  • +

Replies To: how to print N numbers in descending order

#2 PostulateMan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 50
  • Joined: 14-September 08

Re: how to print N numbers in descending order

Posted 20 February 2009 - 08:52 AM

Hey yvsham. Looks like you've got the right idea, you just need to brush up on your for loop syntax. You currently have:

for(i=0;i+1;i++)



The syntax for a for loop is:
for( (initializer list); (conditional); (iteration) )

You have the right idea in the first part. You initialize i to 0, but if you start as zero and count up you get ascending order.

The second statement in the for loop is used to check a condition. Right now you have i+1, which will always be true. Here you want to check for when to stop. Commonly, you can check if i < someNumber or that (hint hint) i >= 0.

The third part you use correctly, but again, you are set up to use the for loop in ascending order. For descending order the values get smaller. Since ++ adds one to i every time the loop iterates, your values will get larger.


Hope this helps!
Was This Post Helpful? 0
  • +
  • -

#3 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Re: how to print N numbers in descending order

Posted 20 February 2009 - 09:23 AM

this is a bubble sort algorithm!!!
I hope this helps you with some minor changes..............

for (i=0; i<n-1; i++) {
  for (j=0; j<n-1-i; j++)
	if (a[j+1] < a[j]) {  /* compare the two neighbors */
	  tmp = a[j];		 /* swap a[j] and a[j+1]	  */
	  a[j] = a[j+1];
	  a[j+1] = tmp;
  }
}


Was This Post Helpful? 0
  • +
  • -

#4 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Re: how to print N numbers in descending order

Posted 20 February 2009 - 09:32 AM

this is a bubble sort algorithm!!!
I hope this helps you with some minor changes..............

for (i=0; i<n-1; i++) {
  for (j=0; j<n-1-i; j++)
	if (a[j+1] < a[j]) {  /* compare the two neighbors */
	  tmp = a[j];		 /* swap a[j] and a[j+1]	  */
	  a[j] = a[j+1];
	  a[j+1] = tmp;
  }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1