Kurt Peek Kurt Peek - 3 months ago 11
C Question

How to define an array in C

I'm reading the book "Cracking the Coding Interview" which contains several examples of algorithms in C. I'd like to make programs which implement these algorithms and run them as I go along.

One such algorithm is "Min and Max 1" (from the "Big O" chapter):

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int x : array) {
if (x < min) min = x;
if (x > max) max = x;
}


I've attempted to 'write a program around this' as follows:

#include<stdio.h>

int array[5] = [1, 3, 2, 5, 4];

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

int main(void):
{
for (int x : array) {
if (x < min) min = x;
if (x > max) max = x;
}
printf("The minimum is %i", min)
printf("The maximum is %i", max)
}


However, if I try to compile and run this I get the
error: expected identifier before numeric constant int array[5] = [1, 3, 2, 5, 4];
. How would I correctly implement this algorithm for this example input array?

Answer

What you mean is the following

#include <stdio.h>
#include <limits.h>

#define N   5

int main( void ) 
{
    int array[N] = { 1, 3, 2, 5, 4 };

    int min = INT_MAX;
    int max = INT_MIN;

    for ( size_t i = 0; i < N; i++ )
    {
        if ( array[i] < min ) min = array[i];
        if ( max < array[i] ) max = array[i];
    }

    printf( "The minimum is %i\n", min );
    printf( "The maximum is %i\n", max );

    return 0;
}

The program output is

The minimum is 1
The maximum is 5

As for your program then it contains invalid constructions according to the C grammar.

In C++ the loop can look the same way as you showed.

#include <iostream>
#include <limits>

int main() 
{
    const size_t N = 5;
    int array[N] = { 1, 3, 2, 5, 4 };

    int min = std::numeric_limits<int>::max();
    int max = std::numeric_limits<int>::min();

    for ( int x : array )
    {
        if ( x < min ) min = x;
        if ( max < x ) max = x;
    }

    std::cout << "The minimum is " << min << std::endl;
    std::cout << "The maximum is " << max << std::endl; 

    return 0;
}

Take into account that there is no sense to declare the array like global.

As for the array definition in C then you can define it either like

int array[5] = { 1, 3, 2, 5, 4 };

(or using some named constant instead of the number 5)

or like

int array[] = { 1, 3, 2, 5, 4 };

In the last case the number of elements is equal to the number of the initializers. Or even you can use the following initialization

int array[] = { [0] = 1, [1] = 3, [2] = 2, [3] = 5, [4] = 4 };