第8回演習の解答例


要素数 10 個の整数型配列 {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7}がある.

(1) 配列の要素すべての,要素番号と値を表示するプログラムを作成せよ.


#include <stdio.h>
 
void main()
{
    int a[10] = {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7};
    int i;
 
    for(i=0; i<10; i++){
			printf("a[%d]=%d¥n",i,a[i]);
    }
}

(2) 配列の要素すべての数の積を計算し結果を表示するプログラムを作成せよ.


#include <stdio.h>
 
void main()
{
	int a[10] = {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7};
	int i;
	int seki;

	seki = 1;
 
	for(i=0; i<10; i++){
			seki *= a[i];
	}

	printf("積:%d¥n",seki);

}

(3)要素数 12 個の整数型配列 {9, 8, 7, -6, -7, 5, 3, 10, 0, 7, -3, 1}の中から数字の 5 を探し,
   5が存在「する」または「しない」を表示するプログラムを作成せよ


#include <stdio.h>
 
void main()
{
    int a[10] = {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7};
    int i, count;
    
    count = 0;
 
    for(i=0; i<10; i++){
        if(a[i]==5){
			count++;
		}
    }
 
    if(count!=0){
		printf("この配列には5が存在する¥n");
	} else {
		printf("この配列には5が存在しない¥n");
	}
}

(4) 配列の中に数字の 7 がいくつあるかを数えるプログラムを作成せよ.


#include <stdio.h>
 
void main()
{
    int a[10] = {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7};
    int i, count;
    
    count = 0;
 
    for(i=0; i<10; i++){
        if(a[i]==7){
			count++;
		}
    }
 
    if(count!=0){
		printf("この配列には7が%d個存在する¥n",count);
	} else {
		printf("この配列には7が存在しない¥n");
	}
}

(5) 配列の最大値を表示するプログラムを作成せよ.


#include <stdio.h>
 
void main()
{
   int a[10] = {-4, 6, 7, 2, -7, 5, 3, 9, 0, 7};
    int i, max;
 
    max = a[0];
 
    for(i=0; i<10; i++){
        if(max<a[i]){
			max = a[i];
		}
    }
 
    printf("この配列の最大値は%dです¥n",max);
}