A
A
Andrey Rudenko2020-11-12 19:09:13
C++ / C#
Andrey Rudenko, 2020-11-12 19:09:13

How to find the sum of negative elements in an array?

Good evening!
Conditions of the problem: Given a one-dimensional array A, consisting of 18 elements. Calculate and print the sum of negative identical elements.

I don't understand how I can calculate the sum of negative values ​​and sort the array so that the same elements can be entered into the scatter (if I enter the same elements into the scatter, nothing works).
Thank you!
Task code:

#include <stdlib.h>
#include <stdio.h>
#define N 18
int main() {
    int i, sum=0;
    int a[N] = {-5, -5, 6, 13, 10, 16, -18, -18, 11, 17, -3, -3, -7, -7, 9, 31, -4, -4};
    printf("Выходные данные = ");
    for (i = 0; i < N; i++) {
        printf("%d ", a[i]);
    }
    printf("\nПарные элементы = ");
    for (i = 0; i < N; i++) {
        if (a[i] == a[i - 1] && a[i] < 0) {
            printf("%i ", a[i]);
            }
        }
        for (i = 0; i < N; i++) {
            sum += a[i] < 0;
        }
        printf("\nСумма отрицательных элементов = %d", sum);

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2020-11-12
@FlapsBat

Calculate and print the sum of negative identical elements.

Once

#include <stdio.h>

#define N 18

int main()
{
  int a[N] = {-5, -5, 6, 13, 10, 16, -18, -18, 11, 17, -3, -3, -7, -7, 9, 31, -4, -4};
  int checked[N] = {0};
  int total = 0;

  for(int i = 0; i < N - 1; i++)
  {
    if(a[i] < 0)
    {
      int sum = a[i];
      for(int j = i + 1; j < N; j++)
      {
        if(!checked[j] && a[i] == a[j])
        {
          sum += a[j];
          checked[j] = 1;
        }
      }

      if(sum != a[i])
      {
        total += sum;
      }
    }
  }
  (total) ? printf("total sum %d", total)
          : printf("not found");
  return 0;
}


Two

#include <stdio.h>

#define N 18

int main()
{
  int a[N] = {-5, -5, 6, 13, 10, 16, -18, -18, 11, 17, -3, -3, -7, -7, 9, 31, -4, -4};

  int checked[N] = {0};

  int total = 0;

  for(int i = 0; i < N - 1; i++)
  {
    if(a[i] < 0)
    {
      int count = 1;

      for(int j = i + 1; j < N; j++)
      {
        if(!checked[j] && a[i] == a[j])
        {
          count++;
          checked[j] = 1;
        }
      }

      if(count > 1)
      {
        total += a[i] * count;
        // Тут сложение можно заменить умножением
        printf("number %d count %d sum %d\n", a[i], count, a[i] * count);
      }
    }
  }
  (total) ? printf("total sum %d", total)
          : printf("not found");
  return 0;
}

R
Rsa97, 2020-11-12
@Rsa97

https://habr.com/en/post/335920/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question