Array Problem

This is what I try to do: Take an integer array of leght 5 call num and return the max in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const int NUM = 5
int max[NUM];
int i; 
int max2;

for (i=0; i < NUM; i++) 
{
   if (max [i] > max2)
   {
       max2 = max[i];
   }
}
return 0


can someone kind check for me if it correct or show me how to check it. One more thing how do you the index of the max value (same value).


Can anyone have help with this also?

write a function that take a and b and return and array which store the sum of correspond elemets.

1
2
3
4
5
6
7
8
9
10
11
12
const int NUM = 10
int a [NUM];
int b [NUM];
int c=0
for (int d = 0; d < e ; d+)
{
if (int e=0;e<b; e++)
{
c+=a+b;
}
}



Just learn how to do array!
Last edited on
First of all, organize yourself and make a function my_max that takes an integer array a and its size n and returns the largest element in a:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int my_max(int a[], int n)
{
    int m = a[0];

    for (int i = 1; i < n; i++)
    {
        if (a[i] > m)
        {
            m = a[i];
        }
    }

    return m;
}


Then, to test it, come up with a few test cases and see if the results you get make sense. For example, if I pass int a[] = { 1, 5, 2, 14, 8, 1 }, and n = 6, I should obtain 14.
oh okay thx Josue Molina! but your example i dont somewhat dont understand. since i have put 5 for a? and plus how can you find index of max value?
Last edited on
If you are looking for the index of the largest element, then modify the above function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int my_max(int a[], int n)
{
    int m = 0;

    for (int i = 1; i < n; i++)
    {
        if (a[i] > a[m])
        {
            m = i;
        }
    }

    return m;
}
I dont understand where should I put 5? Should I put int m = 5
Last edited on
n should be equals to 5. m is a temp to store the current max value, if found some value greater than m in the looping process, m will be replaced by the greater value. Till the end of the loop, m shall be the greatest value in your array.
oh ok thank!

Can anyone have help with this also?

write a function that take a and b and return and array which store the sum of correspond elemets. can someone check if this correct or not or show me how to do to check?

1
2
3
4
5
6
7
8
9
10
11
12
const int NUM = 10
int a [NUM];
int b [NUM];
int c=0
for (int d = 0; d < e ; d+)
{
if (int e=0;e<b; e++)
{
c+=a+b;
}
}
Last edited on
I believe you need to review the basics because your if statement is incorrect, but here you go anyway:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Assumption: a, b, and c have a size of n.
void add_arrays(int a[], int b[], int c[], int n)
{
    for (int i = 0; i < n; i++)
    {
        c[i] = a[i] + b[i];
    }
}

// Example:
int n = 3;
int a[n] = { 1, 2, 3 };
int b[n] = { 4, 5, 6 };
int c[n];
add_arrays(a, b, c, n); // c = { 5, 7, 9 } 
Thank you so much Joseue
Topic archived. No new replies allowed.