Tìm phần tử đầu tiên của mảng lớn hơn 2016

Yêu cầu:
– Cho mảng số thực
– Tìm phần tử đầu tiên trong mảng thỏa mãn lớn hơn 2016. Nếu không tìm thấy, trả về -1.

Giải thuật:

Code

/************************************************************
* Author: VNCODING
* History
* 2016/12/21        first create    VNCODING
*************************************************************/

#include <stdio.h>
#include <conio.h>
#include <math.h>

#define MAX_SIZE_ARR 100

float get_first_element_greater_2016(float arr[], int sz);

int main()
{
    float arr[MAX_SIZE_ARR];
    int n, i;
    float res;
    do
    {
        printf("n = ");
        scanf("%d", &n);
    }while(n <= 0 || n > 100);
    
    // Input array
    for(i = 0; i < n; i++)
    {
        printf("\narr[%d] = ", i);
        scanf("%f", &arr[i]);
    }
    res = get_first_element_greater_2016(arr, n);
    if (res == -1)
    {
        printf("\nNot found!!!");
    }
    else
    {
        printf("\nThe first element is greater than 2016 that is: %f", res);
    }
    getch();
    return 0;
}

float get_first_element_greater_2016(float arr[], int sz)
{
    int i;
    for (int i = 0; i < sz; i++) 
    { 
        if (arr[i] > 2016)
        {
            return arr[i];
        }
    }
    return -1;
}

Kết luận:

Tìm phần tử đầu tiên trong mảng lớn hơn 2016
Tìm phần tử đầu tiên trong mảng lớn hơn 2016

3 Comments on Tìm phần tử đầu tiên của mảng lớn hơn 2016

Leave a Reply to Phát Lê Cancel reply