1.從鍵盤上輸入5個數,輸出最大的、最小的元素以及他們的下標
#include
int main(void)
{
int i, j, k, max, min;
int a[10] = {0};
printf("input number:");
for(i = 0; i < 5; i++)
scanf("%d", &a[i]);
max = min = a[0];
j = k = 0;
for(i = 0; i < 5; i++)
{
if(max < a[i])
{
max = a[i];
j = i;
}
else if(min > a[i])
{
min = a[i];
k = i;
}
}
printf("%d %d %d %d\n", j, max, k, min);
return 0;
}
2.從鍵盤上輸入16個整數,保存在4*4的二維數組中輸出偶數行和偶數列的元素。
#include
int main(void)
{
int a[5][5] = {0};
int i, j;
printf("input numbers:");
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
scanf("%d", &a[i][j]);
for(i = 0; i < 4; i++)
for(j = 0; j < 4; j++)
{
if(i % 2 == 0 && j % 2 == 0)
printf("%d\n", a[i][j]);
}
return 0;
}
3.在有序數組中,輸入一個數,若這個很數存在,則輸出數及其位置,若不存在,則輸出信息。
#include
#define M 10
int main(void)
{
int a[M] = {-1,6,8,10,15,20,21,25,29,55};
int n;//查找的數
int low, high, mid;
int found;
low = 0;
high = M - 1;
found = 0;
printf("input n:");
scanf("%d", &n);
while(low <= high)
{
mid = (low + high) / 2;
if(n == a[mid])
{
found = 1;
break;
}
else if(n < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if(found == 1)
printf("index of %d is %d", n, mid);
else
printf("there is not %d", n);
return 0;
}