2

I just started to learn C language. By now I have very basic knowledge. At the moment I am coding some very simple programs from given exercises by my University.

Current exercise I have is: Write a program that finds two largest elements in n element array (2 ≤ n ≤ 10) and outputs sum of those two elements.

The problem is that my written code works only with positive array numbers and doesn't work with negative numbers.

Current code:

#include <stdio.h>

int main() {
    int seka[] = {0,0,0,0,0,0,0,0,0,0}; //array in lithuanian = seka
    int k; //variable to determine array size
    int m = seka[0];
    int n = seka[0];
    int y = 0;

    scanf ("%d",&k);
    for(int i = 0; i < k; ++i){
        scanf ("%d",&seka[i]);
    }

    for(int j = 0; j < k; ++j){
        if (seka[j] > m)
            m = seka[j];
    }

    for(int o = 0; o < k; ++o){
        if (seka[o] == m)
            y = y + 1;
    }

    if(y >= 2){
        n = m;
    }
    else
    {
        for(int l = 0; l < k; ++l){
            if(seka[l] != m)
                if (seka[l] > n)
                    n = seka[l];
        }
    }

    printf ("%d", m + n);
    return 0;
}

Input used:

5
4 9 5 6 3

Output got:

15

But if input has negative numbers:

6
-5 -8 -6 -2 -5 -8

Output is:

0

I know that this is not the most efficient approach for given problem, but I am still learning and I hope that you will help me finding the root of the issue.

Fixed my code with your help, now works like it should.

Fixed code:

#include <stdio.h>

int main() {
    int seka[] = {0,0,0,0,0,0,0,0,0,0}; //array in lithuanian = seka
    int k; //variable to determine array size
    int y = 0;

    scanf ("%d",&k);
    for(int i = 0; i < k; ++i){
      scanf ("%d",&seka[i]);
    }
    int m = seka[0];
    for(int j = 1; j < k; ++j){
        if (seka[j] > m)
        m = seka[j];
    }

    for(int o = 0; o < k; ++o){
        if (seka[o] == m)
        y = y + 1;
    }

    int n;

    for(int l = 0; l < k; ++l){
        if(seka[l] != m)
        if (seka[l] < n)
        n = seka[l];
    }

    if(y >= 2){
        n = m;
    }
    else
    {   
        for(int l = 0; l < k; ++l){
        if(seka[l] != m)
        if (seka[l] > n)
        n = seka[l];
    }
    }

    printf ("%d", m + n);
    return 0;
  }
mezo101
  • 31
  • 4

1 Answers1

4

You update the max value with

for(int j = 0; j < k; ++j){
  if (seka[j] > m)
      m = seka[j];
}

but you initialize it with

 m = seka[0];

The problem is that seka[0] has not been set by the user, yet, so its value is 0. That's Why the maximum value cannot be less than 0.


In order to fix it, just initialize the maximum with the first element of the array, but after the user input. Then loop starting from index 1:

m = seka[0];
for(int j = 1; j < k; ++j){
    if (seka[j] > m)
        m = seka[j];
}
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39