[英]Program not proceeding after taking array input in C
#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d ", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
When I run the code, I am only able to enter the elements of array and thus the program does not proceed further.当我运行代码时,我只能输入数组的元素,因此程序不会继续进行。 What's wrong with the code?
代码有什么问题?
int n,a[n],element;
Is equivalent of saying相当于说
int n;
int a[n];
int element;
Notice something?注意到什么了吗? You're declaring an array of variable size with an uninitialized variable
n
.您正在声明一个具有未初始化变量
n
的可变大小数组。 This leads to unexpected behaviour.这会导致意外行为。 Declare your array after the value of n has been set!
在设置 n 的值后声明你的数组!
int n,element;
scanf("%d", &n);
int a[n];
On observing your code,在观察你的代码时,
#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d", &a[i]); // correction: here you had given space after %d...
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
you had given space scanf("%d ", &a[i]);
你给了空间
scanf("%d ", &a[i]);
after %d
which should not be used, that's why your program is not proceeding after taking array input... I am assuming your binary search operation is correct and working fine...在不应该使用的
%d
之后,这就是为什么你的程序在输入数组后没有继续运行......我假设你的二进制搜索操作是正确的并且工作正常......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.