本文目錄一覽:
C語言題目:在數組中查找指定元素
#include stdio.h
#define MAXN 10
int search( int list[], int n, int x );
int main()
{
int i, index, n, x;
int a[MAXN];
printf(“輸入個數:\n”);
scanf(“%d”,n);
for( i = 0; i n; i++ )
scanf(“%d”, a[i]);
printf(“輸入x:\n”);
scanf(“%d”, x);
index = search( a, n, x );
if( index != -1 )
printf(“index = %d\n”, index);
else
printf(“Not found\n”);
return 0;
}
int search( int list[], int n, int x ){
int i;
for(i=0;in;i++){
if(x==list[i])
return i;
}
return -1;
}
擴展資料:
數組使用規則:
1.可以只給部分元素賦初值。當{ }中值的個數少於元素個數時,只給前面部分元素賦值。例如:static int a[10]={0,1,2,3,4};表示只給a[0]~a[4]5個元素賦值,而後5個元素自動賦0值。
2.只能給元素逐個賦值,不能給數組整體賦值。例如給十個元素全部賦1值,只能寫為:static int a[10]={1,1,1,1,1,1,1,1,1,1};而不能寫為:static int a[10]=1;請注意:在C、C#語言中是這樣,但並非在所有涉及數組的地方都這樣,數據庫是從1開始。
3.如不給可初始化的數組賦初值,則全部元素均為0值。
4.如給全部元素賦值,則在數組說明中, 可以不給出數組元素的個數。例如:static int a[5]={1,2,3,4,5};可寫為:static int a[]={1,2,3,4,5};動態賦值可以在程序執行過程中,對數組作動態賦值。這時可用循環語句配合scanf函數逐個對數組元素賦值。
參考資料:
百度百科-數組
C語言刪除數組指定元素
C語言刪除數組指定元素的源代碼如下:
#include stdio.h
main()
{
char s[80],c;
int j,k;
printf(“\nEnter a string: “);
gets(s);
printf(“\nEnter a character: “);
c=getchar( );
for(j=k=0;s[j]!= ‘\0’;j++)
if(s[j]!=c)
s[k++]=s[j];
s[k]= ‘\0’;
printf(“\n%s\n”,s);
system(“pause”);
}
擴展資料
自定義函數代碼如下
function delarrayval2($arr,$v){
$keyarr = array_keys($arr, $v);
if(count($keyarr)){
foreach ($keyarr as $key) {
unset($arr[$key]);
}
}
return $arr;
}
C語言實現整型數組中查找指定元素的函數?
#includestdio.h
int search(int a[], int n, int searchValue) {
int i;
for(i=0; in; i++) if(a[i]==searchValue) return i;
return -1;
}
int main() {
int i;
int a[10],find,idx;
for(i=0; i10; i++) {
printf(“Input a[%d]:”,i);
scanf(“%d”,a[i]);
}
printf(“Input searchValue:”);
scanf(“%d”,find);
idx=search(a,10,find);
if(idx!=-1) printf(“pos=%d”,idx);
else printf(“not found”);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/239634.html