Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2014
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. /* This program asks the user to enter up to 20 numbers. It then displays the numbers entered, removes duplicates
  5. and then list the numbers with the duplicates removed in ascending order.
  6. */
  7. int main (void)
  8.  
  9. { //Variables
  10. setbuf(stdout, NULL);
  11.  
  12. int nums[20] , i , j, k, swap ;
  13. int count=0;
  14.  
  15. // ===================================================
  16. // Part one. Enter the numbers
  17. printf("Enter integers. (Negative -1 to stop):\n");
  18. for (i=0; i < 20; i++)
  19. {
  20.  
  21.  
  22. scanf("%d", &nums[i]);
  23. count = count +1;
  24.  
  25. if(nums[i] == -1 ) // If user enters -1 stops the program from expecting anymore number inputs
  26.  
  27. break;
  28. }
  29.  
  30. // ===========================================================
  31. //Part 2. Print the numbers entered
  32. printf("The numbers you entered are:\n"); // outputs the numbers you entered one number per line
  33. for(i=0;i<count;++i)
  34. {
  35. printf("%d\n", nums[i]);
  36. }
  37.  
  38. // ============================================================
  39. // Part 3. Display numbers with duplicates removed
  40. printf("\n Your numbers with the duplicate numbers removed:\n ");
  41. // for loop for removing the duplicate numbers that the user enters.
  42. for(i=0;i<count;i++)
  43. {
  44. for(j=i+1;j<count;)
  45. {
  46. if(nums[j]==nums[i])
  47. {
  48. for(k=j;k<count-1;++k)
  49. {
  50. nums[k]=nums[k+1];
  51. }
  52. count--;
  53. }
  54. else
  55. {
  56. j++;
  57. }
  58. }
  59. }
  60.  
  61. for(i=0;i<count;i++) // outputs the numbers you entered with the duplicates removed one number per line
  62. printf("%d\n ",nums[i]);
  63.  
  64. //================================================================
  65. // Part 3. Bubble sort for listing numbers in ascending order
  66.  
  67. // start of the bubble sort for listing the numbers in ascending order. Can replace ">" with "<" to list in descending order
  68. for(i=0; i<count -1; i++)
  69. {
  70. for(j=0; j < count -1 - i; j++)
  71. {
  72. if (nums[j] > nums[j+1])
  73. {
  74. swap = nums[j];
  75. nums[j] =nums[j+1];
  76. nums[j+1] = swap;
  77. }
  78. }
  79. }
  80. printf("\n Your numbers sorted in to ascending order with the duplicates removed:\n");
  81.  
  82. for(j=0;j<count;j++) // outputs the numbers in ascending order. One number per line
  83. printf("%d\n ",nums[j]);
  84.  
  85.  
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement