C language programming (array operation) every day

(1) Write a program to find the maximum value of the sum of sub-arrays in an integer array with N elements. Sub-arrays refer to several consecutive adjacent elements in an array.

int a[7] = {-2, 5, -1, 6, -4, -8, 6};

 Idea analysis

1. Set sum=0, add each element in the array in turn

●If the sum is negative when adding one of the elements (sum<0), then set the sum to 0, because if the sum is negative and continues to add the next element, then the number obtained must not be the largest, for example

sum+a[0]=-2; sum+a[1]=3;----equivalent to consecutive elements starting with the first element

sum+a[0]=-2; sum=0; sum+a[1]=5;------It is equivalent to skipping the consecutive elements after the negative number a[0]

●If sum plus the next element is greater than sum, then assign sum to max

code show as below:

#include <stdio.h>

int main(void)
{
    int a[100];
    int len = 0;

    printf("请输入系列整数,以#结束\n");
    while(scanf("%d", &a[len]) != 0)
        len++;

    int max=a[0], sum=0;

    int i;
    for(i=0; i<len; i++)
    {
        sum += a[i];

        if(sum > max)
            max = sum;

        else if(sum < 0)
            sum = 0;
    }

    printf("最大子数组之和: %d\n", max);
    return 0;
}

(2) Write a function that receives two m×n two-dimensional integer arrays a and b. The function of the function is to copy the data in array a to array b.

This is relatively simple to implement, the code is as follows

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

// 将数组source各个元素的值,赋给数组target
void assign(int row, int col,double target[row][col], double source[row][col])
{
    int i, j;
    for(i=row; i>0; i--)
    {
        for(j=col; j>0; j--)
        {
            target[i-1][j-1] = source[i-1][j-1];
        }
    }
}
//输出源数据和复制后的数据
void show(int row, int col,double target[row][col], double source[row][col])
{
    int i, j;
    printf("源数据:\n");

    for(i=row; i>0; i--)
    {
        for(j=col; j>0; j--)
        {
            printf("%f\t", source[i-1][j-1]);
        }
        printf("\n");
    }

    printf("目标数据:\n");
    for(i=row; i>0; i--)
    {
        for(j=col; j>0; j--)
        {
            printf("%f\t", target[i-1][j-1]);
        }
        printf("\n");
    }
}

int main(void)
{
    int i, j;
    int row, col;
    
    printf("请输入二维数组的行数和列数:\n");
    scanf("%d%d", &row, &col);

    double source[row][col];

    for(i=0; i<row; i++)
    {
        for(j=0; j<col; j++)
        {
            // 往源数组中写入随机数据
            source[i][j] = (double)rand() / (double)rand();
        }
    }

    double target[row][col];

    assign(row, col, target, source);
    show(row, col, target, source);

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_69884785/article/details/131925789