Error while printing sorting array in C language? - c

I am trying make sorting function for an array. I use selection sort in an ascending order but I have no ideas what's wrong with my "output" function and I know that this similar question have been asked on stack-overflow but the answers didn't help me much. The error on Dev C++ show like "[Error] a function-definition is not allowed here before '{' token".
#include<stdio.h>
#include<stdlib.h>
void sort(int arr[], int n)
{
int minindex;
int t,i,j;
for(i=0;i<n-1;i++)
{
minindex=i;
for(j=i+1; j<n; j++)
{
if(arr[minindex]>arr[j])
minindex=j;
}
if(minindex>1)
{
int t=arr[minindex];
arr[minindex]=arr[i];
arr[i]=t;
}
}
void output(int arr[], int n)
{
for(int i=0; i<n; i++)
{
printf("%5d", arr[i]);
}
}
int main()
{
int arr[]={1,3,5,7,9,2,4,6,8,0};
int*a=(int*)calloc(10,sizeof(int));
sort(a,10);
ouput(a,10);
getchar(); getchar();
return 0;
}

If you use CodeBlocks, you can goto Plugins->Source code formatter(AStyle) to auto-format your code. Don't know about DevC++.
Array name is a pointer itself to the location of the first array item in memory. No need to create int* (it is unused in your code)
Do not define a variable until it is being used.
To compare two files, run a diff style program on Linux (or open files up side by side in two windows). If you are on windows, you can use meld.exe.
main() goes before your functions. See function declarations before main(). It is considered better. Still better would be to move functions to another file.
Clicking on a brace '{' should highlight the corresponding brace in any IDE.
Poor indentation almost always exacerbates the missing brace problem.
I am tempted to give you the code, but I am sure you can do the edits yourself.
--- Output
0 1 2 3 4 5 6 7 8 9
Process returned 0 (0x0) execution time : -0.000 s
Press any key to continue.

Related

How would I modify this code so that it prints the output of the path it takes to get from point A to B

This code answers the question: Given a 2 dimensional matrix where some of the elements are filled with 1 and rest of the elements
are filled. Here X means you cannot traverse to that particular points. From a cell you can either traverse to left, right, up or down. Given two points in the matrix find the shortest path between these points.
I need help implementing a way to print the path between the two points, ex (1,3) -> (1,4), etc. Please help
#include <stdio.h>
#include <stdlib.h>
char arr[5][5]={ {'1','1','1','1','1'},
{'1','S','X','1','1'},
{'1','1','1','1','1'},
{'X','1','1','E','1'},
{'1','1','1','1','X'} };
int minimum[20];
int ind=0;
void addToMin(int len)
{
minimum[ind++]=len;
}
int IsInPath(int (*path)[5],int r,int c)
{
if(path[r][c]==0) return 0;
else return 1;
}
int isValid(int r,int c)
{
if((r>=0 && r<=4) && (c>=0 && c<=4))
return 1;
else
return 0;
}
void findMin(int (*path)[5],int len,int r,int c)
{
int path2[5][5];
int i,j;
for(i=0;i<;5;i++)
for(j=0;j<;5;j++)
path2[i][j]=0;
if(arr[r][c]=='E')
{
addToMin(len);
}
else if(arr[r][c]=='X' || (arr[r][c]=='1' && IsInPath(path,r,c)))
{
return;
}
else if((arr[r][c]=='1' && !IsInPath(path,r,c)) || arr[r][c]=='S')
{
for(i=0;i<;5;i++)
for(j=0;j<;5;j++)
path2[i][j]=path[i][j];
path2[r][c]=1;
len++;
if(isValid(r,c-1))
findMin(path2,len,r,c-1);
if(isValid(r-1,c))
findMin(path2,len,r-1,c);
if(isValid(r,c+1))
findMin(path2,len,r,c+1);
if(isValid(r+1,c))
findMin(path2,len,r+1,c);
}
}
int main()
{
int i,j,flag=0,min=9999;
int path[5][5];
for(i=0;i<;5;i++)
for(j=0;j<;5;j++)
path[i][j]=0;
for(i=0;i<;5;i++)
{
for(j=0;j<;5;j++)
{
if(arr[i][j]=='S')
{
findMin(path,0,i,j);
flag=1;
break;
}
}
if(flag==1) break;
}
for(i=0;i<ind;i++)
{
if(minimum[i]<min)
min=minimum[i];
}
printf("Minimum Distance =%d",min);
return 0;
}
regarding Your question: I need help implementing a way to print the path between the two points.
The comment by #Serge gives an excellent method of tracing the path from start to finish, with out also displaying any steps that were not kept. Here is a repeat of that comment:
use an array of x/y pairs or a list to record the path.
increment index on the way forward and decrement it before return (or add/remove last element from the list).
print the contents when reach the endpoint.
You will get a few different paths.
regarding statements like:
for(i=0;i<;5;i++)
the for() statement has 3 parameters separated via semicolons, not 4 parameters. Therefore, the semicolon between the i< and 5 should not be there.
There are several such syntax errors in the posted code.
The posted code contains the 'magic' number 5, buried all through the code. 'magic' numbers are numbers with no basis. 'magic' numbers make the code much more difficult to understand, debug, etc. Suggest:
#define MAX_ROWS 5
#define MAX_COLS 5
Then using those names throughout the code.
regarding:
int i,j,flag=0,min=9999;
and
if(path[r][c]==0) return 0;
else return 1;
Please follow the axiom: only one statement per line and (at most) one variable declaration per statement. I.E.
int i;
int j;
int flag=0;
int min=9999;
and
if( path[r][c]==0 )
return 0;
else
return 1;
or even:
return ( path[r][c] == 0 )? 0 : 1;
regarding:
int path[5][5];
for(i=0;i<;5;i++)
for(j=0;j<;5;j++)
path[i][j]=0;
This can be reduced to:
int path[5][5] = {0};
regarding:
int (*path)[5]
That expression/parameter might work when a parameter is a pointer to a pointer, as when working with a linked list, but is not correct for this problem. Suggest:
int path[][5]
as the main thing the compiler needs to know is the length of each row in the matrix.
For ease of readability and understanding:
Please consistently indent the code. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each indent level be 4 spaces.
insert an appropriate space: inside parens, inside braces, inside brackets, after semicolons, after commas, around C operators.
separate code blocks: for if else while do...while switch case default via a single blank line.
separate functions via 2 or 3 blank lines. Be consistent.
The compiler can read code those formatting is very 'messed up'. However, us humans work best with uniform, clean formatting of code.
regarding:
char arr[5][5]={ {'1','1','1','1','1'},
{'1','S','X','1','1'},
{'1','1','1','1','1'},
{'X','1','1','E','1'},
{'1','1','1','1','X'} };
In C, the compiler can determine the size of such data elements so, unless there is a very good reason to declare the sizes yourself, much better to let the compiler do it. Suggest:
char arr[][] =
{
{ '1','1','1','1','1' },
{ '1','S','X','1','1' },
{ '1','1','1','1','1' },
{ 'X','1','1','E','1' },
{ '1','1','1','1','X' }
};
Please explain the meaning of S, E, and X as their meaning is not clear from your question, nor easily derived from the posted code.
it is good coding/design practice to limit the scope of variables. Therefore statements like:
for( i=0; i<5; i++ )
are much better written as:
for( int i=0; i<5; i++ )
also, since indexes like 'i' will never be <0, much better to use size_t, as in:
for( size_t i=0; i<5; i++ )

for loop unexceptional behaviour in 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.

Program crashes in Dev C++ when I compile and run

When I run this program in Dev C++, it executes until "enter the no of elements u want in an array" and when I give 5 numbers as input it crashes.
Can anyone help me out?
here is an implementation of quick sort using c
#include<stdio.h>
#include<stdlib.h>
void swap(int *a,int *b)//function to swap array
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void quicksort(int arr[],int start,int end)//function for performig quicksort
{
if(start>=end)
{
return;
}
else
{
int pindex= partition(arr,start,end);
quicksort(arr,start,pindex-1);
quicksort(arr,pindex+1,end);
}
}
int partition(int arr[],int start,int end)//function to partition the array
{
int i;
int pivot=arr[end];//always making the last element in the array as pivot
int pindex=arr[start];
for(i=0;i<end;i++)
{
if(arr[i]<=pivot)
{
swap(&arr[i],&arr[pindex]);
}
swap(&arr[pindex],&arr[end]);
}
}
void display(int arr[],int n)//function to display the sorted array
{
int i=0;
for(i=0;i<n;i++)
{
printf("%d",arr[i]);
}
}
void main() // main function initializing here
{
int n,i,arr[20];
printf("enter the no of elements u want in an array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
printf("\n");
}
quicksort(arr,0,n);
display(arr,n);
getch();
}
This is my complete code of quick sort program.i used different functions for different displaying output,swapping numbers partitioning etc.
the posted code does not even come close to compiling.
strongly suggest compiling with all warnings enabled
(for gcc at a minimum use: -Wall -Wextra -pedantic to enable warnings
Fix the warnings.
Then re-post the code
Just for your information:
use: int main( void ) or int main( int argc, char *argv[] )
place a prototype for each function, other than main(),
at the beginning of the file, just after the #include statements
the conio.h header file is not portable (so should not be used)
suggest using stdlib.h
any function that is not a void return type must have a
return value; statement
the function: getch() is not portable (so should not be used)
suggest using getchar()
in general, for code layout, use:
'#include' statements
blank line
'#define' statements
blank line
'static' file scope variables
blank line
prototypes for all functions except main()
blank line
'int main()' function
blank line
each sub function, separated by a blank line
given this code:
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
printf("\n");
}
the user will see a prompt for the initial input, then only a blinking cursor.
A second prompt for the actual values, along with the directive to only enter one value per line would be good coding practice.
When calling scanf() (and family of functions) always check the returned value (not the parameter value) to assure the input operation was successful.
Suggest, in the existing prompt to the user, add the max value (20) and check in the code that the user entered value is less than 21.
Suggest, for the initial scanf() to change the format specifier to "%u" to assure the user cannot enter a negative value.
Suggest, checking the user did not enter 0 for the number of elements
Since the user will be entering values in any of several different ways, what if they entered:
5 1 2 3 4 5
The call to printf() in the middle of the input loop will result in 5 blank lines being inserted into the terminal. This would not be desirable.
Suggest removing the current printf() from the input loop

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