for loop unexceptional behaviour in C - c

In c programming I write a code as below :
But the problem is first for loop not working properly, means the for loop gets executed only 1 time not t times and some times when first for loop works then output does print yes or no only for l=1 and from l=2 to l=t ,it prints blank screen.
int t,i,n,arr[n+1],j,k,l,flag,x,y;
scanf("%d",&t);
for(l=1;l<=t;l++)
{
scanf("%d",&n);
for(i=1;i<n+1;i++)
{
scanf("%d",&arr[i]);
}
for(k=1;k<n;k++)
{
for(j=k+1;j<n+1;j++)
{
if(arr[k]==arr[j])
{
flag=1;
}
else if(arr[k]!=arr[j])
{
x=arr[k];
y=arr[j];
if(arr[x]==arr[y])
{
flag=2;
printf("YES");
break;
}
}
}
if(flag==2)
{
break;
}
}
if(flag==1)
{
printf("NO");
}
}

This is impossible to diagnose without more context, but here's a huge red flag:
for(i=1;i<n+1;i++)
{
scanf("%d",&arr[i]);
}
You don't show the declaration of arr, but 1-indexing into an array is a very good way of shooting yourself in the foot. Remember that an N-element array in C has valid indexes of 0 to (N - 1), inclusive.
If the above overwrites the array, you get undefined behavior, which of course could make the outermost loop terminate early.
UPDATE: Now that you do show the declaration of arr, we can have a look:
int t,i,n,arr[n+1],j,k,l,flag,x,y;
This is ... very broken, since n is uninitialized at the point where it's being used in the VLA, this gives you undefined behavior. I'm actually a bit surprised your compiler accepted this. I tried building it on ideone.com and it failed, saying:
error: ā€˜nā€™ is used uninitialized in this function [-Werror=uninitialized]
Perhaps you should upgrade your compiler too, and make sure you enable all warnings you can since you seem a bit unsure about the very basics of the language.

Another problem is here:
int t,i,n,arr[n+1],j,k,l,flag,x,y;
// ^ ^
// | |--- non initialized n used here
// |
// |-- n declared here bot not initialized
when arr[n+1] is declared, the content of n is undetermined.
You probably want something like this:
int t,i,n,j,k,l,flag,x,y;
scanf("%d",&t);
for(l=1;l<=t;l++)
{
scanf("%d",&t);
for(l=1;l<=t;l++)
{
scanf("%d",&n);
int arr[n+1];
for(i=1;i<n+1;i++)
{
scanf("%d",&arr[i]);
}
...
There are most likely more errors elsewhere. See also the other answer.

Related

code with array subscript references and pointer dereferencing compiles and runs but the results are unexpected

Why this program can compiling and run but the result is out of my expectation?`
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i++)
{
printf("%c",message[i]);
}
return 0;
}
But this one can meet my expection.(print "hello" rightly)
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i++)
{
printf("%c",*message++);
}
return 0;
}
In the C language,arr[i] is equal to *arr.But in the cases I show above,the result is totally different,when I run them in the devc++.Due to my limited knowledge ,I can't understand this.
Because I'm a student who is going to be a freshman after this summer vacation and only have some konwledge about C language,please answer my question in a more acceptable way. Thanks in advance!
***sorry ,the problem is caused because of my carelessness.I have learned my mistake.
In the C language, arr[i] is equal to *arr....
No, *arr is equal to arr[0].
In your first example, you type message++ which make et points on the next character.
So, the first code can be corrected that way:
for(int i=0; message[i]!='\0'; i++)
{
printf("%c",message[i]);
}
And the second can be simplified: (you don't need i):
for( ;*message!='\0'; )
{
printf("%c",*message++);
}
In the first code, the pointer message isn't changed and what the pointer message points at is also not changed, so the condition *message!='\0' is always true (doing 'h'!='\0').
Therefore, i will continuously be incremented and become so large that message[i] goes out of a region where access is allowed.
The condition should be message[i]!='\0' to avoid this error.
If you want to stick to use * operator for some reason, it should be *(message+i)!='\0'.
I rewrite the program with a slightly different appearance
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0; 'h'!='\0';i++) // notice the change here
{
printf("%c",message[i]);
}
return 0;
}
You see the problem now?
*message is always h, it's not changing with the loop iteration. The comparison is meaningless here, it does not terminate the loop as expected.
You need to ensure that you change the pointer to the next address every time you iterate, to ensure you are checking the value of the next element.
You can make use of the index value, like
for(int i=0; * (message + i) !='\0';i++)

C minimum function always returning 2686916

I am doing a simple function that returns the minimum integer from numbers given from the user(array).
However, it always print 2686916 at the end. Here is my code:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums;
int num;
int sum=0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest){
smallest=nums;
printf("the smallest %d\n,smallest);
return 0;
}
}
I'm not sure what I'm doing wrong.
My friend, it seems you are new to C, and before you ask questions like this one you should try to follow some tutorials for C. You might try something like this.
If the question you ask is not clear or the code you post won't compile anyway it is very hard to help you out. For now this is all I can do:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums = 0; //Always Initialize your variables!
int num = 0;
int sum= 0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest)
{
smallest=nums;
printf("the smallest %d\n",smallest);
}
return 0; //Don't put this in a place that might not be executed!
}
Now it should at least compile, it still doesn't do anything useful as far as I can see. You compare "nums", a variable you didn't use before, with the biggest value of an int, set it to the never used "nums" and print it.
You might want use "sums" or "ar[i]" in the if statement instead, and printing one of these values.(still not 100% sure what you want to do).
Some tips for next time (before you ask a question!):
Variables should always be initialized
In your code you try to use the value of "nums" before it gets a value, this might cause errors or strange results in your code.
Don't put a return in a place that might be skipped,
In your code, "nums" would be bigger than "smallest" (unlikely, bit for example), the code would skip the if statement and never reach the return.
Read your compiler warnings
The code you posted can't compile, read your errors and warnings, and fix them.
(tip) Use better variable names, using names like nums, num and sum make it easy to overlook a mistake.

Segmentation error in c program

I am getting segmentation error when trying to do this simple c sorting program
I am a novice in C language . And can you please explain me why i am getting segmentation error
#include<stdio.h>
int main(void)
{
int prev,next,result,total_number;
int i,j=1,b;
int a[i];
printf("Number of values to be entered");
scanf("%d",total_number);
printf(" enter the values \n");
for(i=0;i<=total_number-1;i++)
{
printf(" enter the values \n");
scanf("%d",a[i]);
}
for(i=0;i<=total_number-2;i++)
{
for(j=1;j<=total_number-1;j++)
{
if(a[i]>a[j])
{
b=a[i];
a[i]=a[j];
a[j]=b;
}
else
{
break;
}
}
}
for(i=0;i<total_number-1;i++)
{
printf("The numbers are %d",a[i]);
}
}
The segmentation fault is caused by this line:
scanf("%d",total_number);
You're missing the address of (&) operator, it should be like this:
scanf("%d",&total_number);
The operator is also missing in this line:
scanf("%d",a[i]);
You can find more details on scanf in the glibc manual:
Another area of difference between scanf and printf is that you must remember to supply pointers rather than immediate values as the optional arguments to scanf; the values that are read are stored in the objects that the pointers point to. Even experienced programmers tend to forget this occasionally, so if your program is getting strange errors that seem to be related to scanf, you might want to double-check this.
But there are other subtle errors in your code, too: the fact the int i in array[i] is not initialized leads to undefined behaviour i.e., anything could happen. You can use malloc to allocate space for the array, but a simple reordering could be enough:
scanf("%d",&total_number);
int a[total_number];
Uses user input to allocate the array.
Lastly, it seems like you're trying to implement an insertion sort algorithm, but the logic is slightly flawed: even correcting the bugs in the code the input
1 3 5 0
gets "ordered" to
1 5 3 0
But I don't know what you were trying to implement. In case you were actually trying to implement insertion sort, you could use the pseucode from the insertion sort wiki article to get an idea of what's missing in your implementation.
int a[i]; is creating an array of arbitrary size since i is not initialized.
Instead, you can dynamically create the equivalent of an array of int once you know total_number.
int* a;
. . . snip . . .
/* once you know total_number */
a = (int*) malloc(total_number, sizeof(int));
/* you can use a with array notation as long as you stay in bounds */
a[i] = something;
/* don't forget to free a when you are done */
free(a);

Why my code is getting Runtime error?

It took me 3 hrs to get the logic to solve the question and code accordingly. But now I am
getting this runtime error. Can anyone please help me to know what mistake I am doing ?
Edit : Its running now but not printing anything.
http://ideone.com/2YlS9J
#include <stdio.h>
#include<math.h>
float distance(float n1,float m1,float n2,float m2){
float d=0;float sum=0;
d =sqrt(pow(m2-m1,2)+pow(n2-n1,2));
sum+=d;
printf("%.2f",sum);
return sum;
}
int main(void) {
int t,n,i,j;float sum=0;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int r=0,s=0,a=0,b=0;
int x[n],y[n],p[n],q[n],min[n],max[n];
for(i=0;i<n;i++){
scanf("%d %d",&x[i],&y[i]);}
for(j=0;j<10001;j++){
for(i=0;i<n;i++){
if(j==x[i]){
p[r++]=x[i];q[s++]=y[i];
}
}}
for(i=0,j=i+1;i<n,j<n;i++,j++){
if(p[i]==p[j]){
if(q[i]>q[j]){min[a++]=p[i]; max[b++]=q[i];}
else{min[a++]=p[i]; max[b++]=q[j];}
}
else{min[a++]=p[i]; max[b++]=q[i];}
}
for(i=0;i<n;i++){
distance(min[i],max[i],min[i+1],max[i+1]);
}
}
}
As #YePhicK said, and I'll emphasize, learn to use a debugger.
Don't rely on guesswork or just eyeballs.
That said, I see something that, unless you really know what you're doing, is certain to break.
You have a loop using j as its index variable.
Then inside it, you have another loop that also uses j as an index variable.
for(j=0;j<10001;j++){ // <----- j used here
for(i=0;i<n;i++){
if(j==x[i]){
p[r++]=x[i];q[s++]=y[i];
}
}
for(i=0,j=i+1;i<n,j<n;i++,j++){ // <----- j used here
if(p[i]==p[j]){
if(q[i]>q[j]){min[a++]=p[i]; max[a++]=q[i];}
else{min[a++]=p[i]; max[a++]=q[j];}
}
else{min[a++]=p[i]; max[a++]=q[i];}
}
}
Also, you are using arrays called min and max.
There are commonly accepted macros called min and max, so if you redefine those you run the risk of a name collision.
Also, in code like this
{
min[a++]=p[i];
max[a++]=q[i];
}
it looks like you are putting empty spaces into arrays min and max by incrementing a twice.
This line:
int x[n],y[n],p[n],q[n],min[n],max[n];
is not correct. In C/C++ you cannot declare plain arrays of a variable size (unlike, say, in Basic). The size of such an array must be known at compile time.
Possible solutions are:
Use dynamic memory (malloc()/free())
Use a statically allocated arrays with a set maximum size (and either run a risk of buffer overflow and memory corruption or make sure you use no-more-than the space you have allocated for)
Use std::vector<int>
for(i=0,j=i+1;i<n,j<n;i++,j++)
The above for() statement contains the following (nonsensical) conditional expression:
i<n,j<n
Change this to one of the following:
i<n || j<n
or:
i<n && j<n
Also, variable 'float sum=0;' in 'main()' is unused; and main() should include a 'return(0);', or similar, at the end.

Number spiral in C, code not working

I want to make a spiral in C using a 2D matrix, such as the one shown below:
This is the code that I worked out. But it keeps going into an infinite loop. I can't seem to get an output. Can anyone tell me what mistake I'm making in this logic?
And I know its pretty cumbersome, but the assignment is to get the output for any "n" dimensional array, and we need to use all the row_left,row_right, etc variables, as they're given in the question.
#include<stdio.h>
int main(void)
{
int array[6][6]={1},dim,row_right=0,row_left=dim-1,col_up=0,col_down=dim-1;
int i,j,num,cnt;
printf("Enter the dimensions of 2D array:\n");
scanf("%d",&dim);
num=dim*dim;
cnt=0;
while(cnt!=num)
{
for(j=col_up;j<=col_down;j++)
{
if(j=0)
array[row_right][j]=1;
else
array[row_right][j]=array[row_right][j-1]+1;
}
for(i=row_right+1;i<=row_left;i++)
array[i][col_down]=array[i-1][col_down]+1;
for(j=col_down-1;j>=col_up;j--)
array[row_left][j]=array[row_left][j+1]+1;
for(i=row_left-1;i>row_right;i--)
array[i][col_up]=array[i+1][col_up]+1;
row_right++;
row_left--;
col_up++;
col_down--;
cnt++;
}
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
printf("%d\t",array[i][j]);
printf("\n");
}
return 0;
}
if(j=0)
is almost surely wrong. This sets j to zero and always evaluates to a false condition. The correct condition uses j == 0.
Also, the code uses the variable dim before it is read by scanf.
You forgot to initialize the variable dim. That is used in following line :
int array[6][6]={1},dim,row_right=0,row_left=dim-1,col_up=0,col_down=dim-1;
With correctly formatted code you probably would have seen this.

Resources