0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語 配列の最大値を求めるコードいろいろ

Last updated at Posted at 2020-03-09

配列と配列数が与えられる。インクリメントでミスが内容に、最初と最後に最大値があるテストケースを用意した。

    int a[6] = {1,3,4,8,7,7};
    int b[6] = {1,3,4,5,7,8};
    int c[6] = {8,3,4,5,7,1};
    int n = 6;

forと配列を使った書き方

int arrayMax(int *a, int n)
{
    int max = 0;
    for(int i = 0; i < n; i++){
        if(max < a[i]){
            max = a[i];
        }
    }
    return max;
}

forとポインタを使った書き方

int arrayMax(int *a, int n)
{
    int max = 0;
    for(int i = 0; i < n; i++){
        if(max < *a){
            max = *a;
        }
        a++;
    }
    return max;
}

whileと配列を使った書き方

int arrayMax(int *a, int n)
{
    int max = 0;
    while(n > 0){
        n--;
        if(max < a[n]){
            max = a[n];
        }
    }
    return max;
}

whileとポインタを使った書き方

int arrayMax(int *a, int n)
{
    int max = 0;
    while(n > 0){
        if(max < *a){
            max = *a;
        }
        a++;
        n--;
    }
    return max;
}
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?