Why my code is getting Runtime error? - c

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.

Related

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.

finding how many times an element has repeated in c

I've got a c study which it must print all the numbers in an array then how many times they repeated.
int lottery(int a,int b,int c,int d,int e,int f,int i,int count)
{
printf("Enter the loop count:");
scanf("%d",&d);
a=time(NULL);
srand(a);
int genel[100][100];
int hepsi[50]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49};
count=0;
for(e=0;e<=d-1;e++)
{
for(b=0;b<=5;b++)
{
genel[e][b]=(rand()%49+1);
while(i>=0 && i<=49)
{
if(genel[e][b]==hepsi[i])
{
count=count+1;
}
else{
count=count;
}
}
printf("%d->%d\t",genel[e][b],count);
}
}
}
This doesnt work obviously. the output must be something like that
1-->0 2-->3 3-->15 etc
TY for your help, cheers :)
It is important that you understand what you are doing, naming is therefore very important. Nesting loops is okay if you know what you are doing. An easier to understand approach would be:
void lottery() {
int i, j //forloop counters
int randArray[100][100]; //array for random values
srand(Time(NULL)); //set random seed based on system time
//set random values
for(i = 0; i < 100; i++) {
for(j = 0; j < 100; j++) {
randArray[i][j] = rand()%49 + 1; //sets random ranging from 1 to 49 (49 incl)
}
}
//here you can start the counting procedure, which I won't spoil but ill give some hints below
}
There are a few options, first the easy lazy approach:
use a loop over all the values, 'int number' from 1 up to 49, inside that forloop use two forloops to search through the whole array, incrementing int x everytime you encounter the value 'number'. After youve searched through the whole array, you can use printf("%d -> %d", number, x); to print the value, set x to zero and count another number.
Another approach is as u tried,
create an array with for each number a location where you can increment a counter. Loop through the whole array now using two for-loops, increment the arraylocation corresponding to the value which youve found at randArray[i][j]. Afterwards print the array with counts using another forloop.
I suggest you try to clean up your code and approach, try again and come back with problems you encounter. Good luck!
sorry if this wasn't helpful to you, I tried to spoil not too much because according to my own experience programming should be learned by making mistakes.

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.

Print the number that appears the maximum number of times in the sequence

Recently I have gone through a problem like this
Write a program to read a sequence of N integers and print the number that
appears the maximum number of times in the sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range [-100,100]
I have writen the following code:
main()
{int arr[201],max=0,maxelement,n,i,num;
int t;
scanf("%d",&n);
int *storenum=(int *)malloc(sizeof(int)*n);
for(i=0;i<201;i++)
{
arr[i]=0;
}
for(i=0;i<n;i++)
{
scanf("%d",&num);
storenum[i]=num;
if(num<=100 && num>=-100)
{
arr[num+100]=arr[num+100]+1;
}
}
for(i=0;i<n;i++)
{
int t=storenum[i]+100;
if(arr[t]>max)
{ maxelement=storenum[i];
max=arr[t];}
}
printf("\n\n%d",maxelement);
getch();
}
Now I think this code is not optimized one...I want to have a solution that would have less time and space complexity and better solution.
You don't have to iterate through all N items a second time, just iterate through the 201 counts looking for the largest.
Your code looks very close to optimal. It can be made only a little better given your constraints.
Use memset when you mean memset. Yes the compiler will pick it up 99% of the time, but why bother?
for(i=0;i<201;i++) arr[i]=0; // becomes
memset(arr, '\0', sizeof(arr))
The count for any given item can be no larger than 10000. That means it can be held in a ushort!
int arr[201]; // becomes
uint16_t arr[201];
Your second loop should go from for(i = -100; i <= 100; i++) instead, and just loop over arr.
Your code is butt-ugly. Use a consistent indentation, brace style, and don't cram 50 declarations on the same line. Spaces are okay between elements. arr should probably be named something meaningful, I like counts. It kind of looks like you're trying to use gnu style C, but K&R works too, really just pick any style guide and glance through it.

10 element array

My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.
Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.
Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram
Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}

Resources