Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Find the next max number from an array using greedy method

bigBelly

New Coder
I am new to programming and I have to do a little program that has an array of n elements and i have to find the largest 4 numbers and to calculate the sum of them.

Sorry if i didn t used the code function very good, but on phone i have some issues with the editor.

Thanks for your help!

As an example: input is 3 7 8 1 6 9 8 5 output: 9887 sum 32

My code takes as output 9 8 7 6 (doesn t display 8 for the second time)

C:
    #include <stdio.h>
    #include <stdlib.h>

int maxim(int a, int b)
{
  if( a > b)
 
    return a;
  else
    return b;
}

int main() {
  int i, j, n, a[999], m, aux, sum = 0, v[999], k = 0, x[999], c, t=0, q, r;
  int max = 0;

  printf("No. of objects (type 8): ");
  scanf("%d", &n);

  printf("\nNo. of objects for first place (type 4): ");
  scanf("%d", &m);

  for(i = 0; i < n; i++)
  {
    scanf("%d", &a[i]);
  }


r = m;

  for (i = 0; i < n; i++)
  {
    if(a[i] > max)
    {
      max = a[i];
    }
  }
      x[0] = max;
  for(i = 1; i < n; i++){
  max = 0;
    for(j = 0; j < n; j++)
    {
      if(a[j] > max && a[j] < x[i - 1])
      {
        max = a[j];
      }
    }
  x[i] = max;
}

  for(t = 0; t < m; t++)
  {
    printf("%d", x[t]);
  }
    return 0;
}
 
I am appalled to see that you define 15 variables for this menial task, three of them arrays, half of them unused by the look of it, as well as a function that you don't use. In fact this bit of code is quite a mess, not to put too fine a point on it. If you would first remove all the clutter, it could either start to work or else someone might help you (assuming that Subba Rao has not already hit the nail - I did not check).
 
Back
Top Bottom