Sorting program stops working without any error - c

I typed the following code to sort the components of an int array. It does not show any error but does stops working abruptly. The error is generally after entering 7-8 inputs which shows that program.exe has stopped working. Does it has anything related to the code ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,a[n],i,j,temp;
printf("Enter number of inputs.\n");
scanf("%d",&n);
printf("Enter inputs\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Numbers in descending order are:\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0;
}

The problem is here:
int n, a[n], i, j, temp;
Declarations are done sequentially. If you write this in a slighly more readably (but equivalent form) you'd have this:
int n;
int a[n]; // here the variable n has not yet been initialized
// it contains an indeterminate value, and therefore the a array
// will have an indeterminate size and the program will have
// so called "undefined behaviour " (google that)
int i;
...
You should write the beginning of your program like this:
int main()
{
int n,i,j,temp;
printf("Enter number of inputs.\n");
scanf("%d",&n);
int a[n]; // now n has a determinate value
printf("Enter inputs\n");
Disclaimer: no error checking is done for brevity.
Always compile with warnings enabled and listen to them. Many of them are actually errors. Especially the warning variable 'somevar' is uninitialized when used here is always an error.

Related

Segmentation Fault linear search algorithm

This algorithm is a linear search algorithm that finds the desired value. But when I compile this code, gives the segmentation fault in if(dizi[i]==aranan) this line. How can I solve this ?
#include <stdio.h>
int N,i,aranan;
int ArrayBastir(int *dizi,int N)
{
printf("My numbers\n");
for(int i =0; i<N;i++)
{
printf("%d\n", dizi[i]);
}
}
int findValue()
{
printf("The value you want to search");
scanf("%d",&aranan);
}
int Output(int *dizi,int N,int aranan)
{
for(int i =0; i<N;i++)
{
if(dizi[i]==aranan)
{
printf("%d number %d. found in queue \n", aranan,i+1);
}
}
}
int main() {
int N;
int aranan;
printf("Please enter how many numbers you want to enter");
scanf("%d", &N);
int dizi[N];
for(int i =0; i<N;i++)
{
scanf("%d", &dizi[i]);
}
ArrayBastir( dizi, N);
findValue(aranan);
Output(*dizi,N,aranan);
return 1;
}
Linear Search algorithm
You have two objects defined as:
int aranan;
Once is defined at file scope (a global), and one is defined within the scope of main.
When findValue(aranan) is called, a copy of the uninitialized value of aranan within the scope of main is passed to findValue. findValue is lacking a prototype, having not declared its arguments, so this is ignored.
findValue scans a value into the file scope aranan, but when Output(*dizi, N, aranan) is called it uses the value of aranan defined within main. aranan within main was never initialized, and thus this causes Output to search for an indeterminate value.
Additionally, *dizi is an int, when Output expects an int * as its first argument.
ArrayBastir and Output are also defined as each returning an int, which they do not do.
You should not ignore the return value of scanf, as it indicates the number of successful conversions, or a negative value on failure (EOF). In a program this small, you can get away with writing a simple wrapper function for reading integers, that just exits the program if the user enters something invalid.
main returning nonzero generally indicates your program failed. main is special - it is the only non-void function where you can omit a return statement. If main reaches the end of execution without an explicit return, it is treated as though it returned 0.
The issues above can be mitigated by avoiding the use of global variables, and by turning up your compilers warning level to catch obvious type mismatches.
For GCC or Clang, use -Wall -Wextra, and possibly -Werror.
For MSVC, use /Wall, and possibly /Wx.
Minimally refactored:
#include <stdio.h>
#include <stdlib.h>
int get_int(void)
{
int x;
if (1 != scanf("%d", &x)) {
fprintf(stderr, "Invalid input.\n");
exit(EXIT_FAILURE);
}
return x;
}
void ArrayBastir(int *dizi, int N)
{
printf("My numbers\n");
for (int i = 0; i < N; i++) {
printf("%d\n", dizi[i]);
}
}
void Output(int *dizi, int N, int aranan)
{
for (int i = 0; i < N; i++) {
if (dizi[i] == aranan) {
printf("Found <%d> at position %d.\n", aranan, i);
}
}
}
int main(void)
{
printf("Please enter how many numbers you want to enter: ");
int N = get_int();
int dizi[N];
for (int i = 0; i < N; i++) {
dizi[i] = get_int();
}
ArrayBastir(dizi, N);
printf("Enter the value you want to search for: ");
int aranan = get_int();
Output(dizi, N, aranan);
}

Cyclic Right Shift for C for an array- time exceeds-infinite loop?

I ran this code and got an time exceed error, It implements cyclic right shift to an array , given array size, elements, and shift width, some help on why this is causing an execution issue would be appreciated,i'm new to this :)
#include<stdio.h>
void main()
{
int n,i;
//array size input
scanf("%d",&n);
int a[n];
//array elements input
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
// shift amount input
int s,temp;
scanf("%d",&s);
//single right shift for S number of times
for(i=0;i<s;i++)
{
temp=a[n-1];
for(i=n-1;i>0;i--)
a[i]=a[i-1];
a[0]=temp;
}
//Output of shifted array
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
Main changes are required in that s nested loop as you used same variable in both outside and inside loops.
Corrections are marked as below:
live demo http://ideone.com/DaokVy
#include <stdio.h>
int main() // use properly
{
int n,i;
//array size input
scanf("%d",&n);
int a[100]; //edit
//array elements input
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
// shift amount input
int s,temp,j;
scanf("%d",&s);
for(i=0;i<s;i++)
{
temp=a[n-1];
for(j=n-1;j>0;j--) // use different variable here
a[j]=a[j-1];
a[0]=temp;
}
//Output of shifted array
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
return 0; // exit success
}

Passing arrays into functions, file.exe stopped working

I am a complete beginner in C and I am practicing passing arrays into functions. I wrote a program to take a two dimensional array as input and find sum of the individual columns.
And when I compiled the program I got no errors, but once I run it, I get a dialogue box saying "untitled5.exe stopped working" where untitled5 is the file name.
I got this error quite a few times. I have used both dev c++ and codeblocks to compile my program, so what is the reason for this? Is this a problem with my code or with my compiler or with my laptop?
#include<stdio.h>
void summation (int arr[][5], int size);
int main()
{
int n,arr[n][5],sum,i,j;
printf("enter the number of rows");
scanf("%d",&n);
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr,5);
return 0;
}
void summation (int arr[][5], int size)
{
int i,j,s=0;
for(j=0;j<5;j++)
{
for (i=0;i<5;i++)
{
s=s+arr[i][j];
}
printf("%d",s);
}
}
In main() you are using i to index the first dimension of the array. In summation() you are using i to index the second dimension of the array. I think that you are going beyond the end of the first dimension inside summation() when main() does not fill up that much of the array (e.g., when you enter 2 for the number of rows).
I think you want
summation (arr,5);
And, inside summation():
for (i=0;i<size;i++)
{
s=s+arr[i][j];
}
#include<stdio.h>
void summation (int arr[][5], int size, int rows);
int main()
{
int n, sum, i, j;
printf("enter the number of rows");
scanf("%d",&n);
int arr[n][5];
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr, 5, n);
return 0;
}
void summation (int arr[][5], int size, int rows)
{
int i,j,s=0;
for(i=0;i<rows;j++)
{
for (j=0;i<size;i++)
{
s=s+arr[i][j];
}
}
printf("%d",s);
}
So first off I moved your array declaration to after you have initialized n and made it equal to something.
Then your next problem was you were probably going out of bounds in your summation function. You always have 5 columns in your 2darray, but you can have a different amount of rows. Pass the amount of rows, n, into the function summation to make sure you don't go out of bounds.

Odd-Even Sort using cuda Programming

I'm trying to implement odd-even sort program in cuda-c language. But, whenever I give a 0 as one of the elements in the input array, the resulted array is not properly sorted.In other cases, however, it is working for other input.I don't understand what is the problem with the code.Here is my code:
#include<stdio.h>
#include<cuda.h>
#define N 5
__global__ void sort(int *c,int *count)
{
int l;
if(*count%2==0)
l=*count/2;
else
l=(*count/2)+1;
for(int i=0;i<l;i++)
{
if(threadIdx.x%2==0) //even phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
{
int temp=c[threadIdx.x];
c[threadIdx.x]=c[threadIdx.x+1];
c[threadIdx.x+1]=temp;
}
__syncthreads();
}
else //odd phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
{
int temp=c[threadIdx.x];
c[threadIdx.x]=c[threadIdx.x+1];
c[threadIdx.x+1]=temp;
}
__syncthreads();
}
}//for
}
int main()
{int a[N],b[N],n;
printf("enter size of array");
scanf("%d",&n);
print("enter the elements of array");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("ORIGINAL ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
int *c,*count;
cudaMalloc((void**)&c,sizeof(int)*N);
cudaMalloc((void**)&count,sizeof(int));
cudaMemcpy(c,&a,sizeof(int)*N,cudaMemcpyHostToDevice);
cudaMemcpy(count,&n,sizeof(int),cudaMemcpyHostToDevice);
sort<<< 1,n >>>(c,count);
cudaMemcpy(&b,c,sizeof(int)*N,cudaMemcpyDeviceToHost);
printf("\nSORTED ARRAY : \n");
for(int i=1;i<=n;i++)
{
printf("%d ",b[i]);
}
}
Your kernel code had two main errors that I could see:
On the odd phase (for even length array, or even phase for odd length array), your last thread will index out of bounds at c[threadIdx.x+1]. For example, for 4 threads, they are numbered 0,1,2,3. Thread 3 is odd, but if you access c[3+1], that is not a defined element in your array. We can fix this by restricting each phase to work on all threads but the last one.
You were using __syncthreads() inside a conditional statement that would not allow all threads to reach the barrier. This is a coding error. Read the documentation. We can fix this by adjusting what code is inside the conditional regions.
In the main code, your final printout statements were indexing incorrectly:
for(int i=1;i<=n;i++)
that should be:
for(int i=0;i<n;i++)
You also have typo here:
print("enter the elements of array");
I assume that should be printf.
The following code has the above errors fixed, and seems to run correctly for me for arrays up to length 5 (your hardcoded limit on N). Even if you increased N, I'm not sure this would work beyond the size of a warp and certainly would not work beyond the threadblock size, but hopefully you are aware of that already(if not, read the doc link about __syncthreads()).
"Fixed" code:
#include<stdio.h>
#include<cuda.h>
#define N 5
#define intswap(A,B) {int temp=A;A=B;B=temp;}
__global__ void sort(int *c,int *count)
{
int l;
if(*count%2==0)
l=*count/2;
else
l=(*count/2)+1;
for(int i=0;i<l;i++)
{
if((!(threadIdx.x&1)) && (threadIdx.x<(*count-1))) //even phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
intswap(c[threadIdx.x], c[threadIdx.x+1]);
}
__syncthreads();
if((threadIdx.x&1) && (threadIdx.x<(*count-1))) //odd phase
{
if(c[threadIdx.x]>c[threadIdx.x+1])
intswap(c[threadIdx.x], c[threadIdx.x+1]);
}
__syncthreads();
}//for
}
int main()
{int a[N],b[N],n;
printf("enter size of array");
scanf("%d",&n);
if (n > N) {printf("too large!\n"); return 1;}
printf("enter the elements of array");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("ORIGINAL ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
int *c,*count;
cudaMalloc((void**)&c,sizeof(int)*N);
cudaMalloc((void**)&count,sizeof(int));
cudaMemcpy(c,&a,sizeof(int)*N,cudaMemcpyHostToDevice);
cudaMemcpy(count,&n,sizeof(int),cudaMemcpyHostToDevice);
sort<<< 1,n >>>(c,count);
cudaMemcpy(&b,c,sizeof(int)*N,cudaMemcpyDeviceToHost);
printf("\nSORTED ARRAY : \n");
for(int i=0;i<n;i++)
{
printf("%d ",b[i]);
}
printf("\n");
}
The usual recital about proper cuda error checking belongs here.

Wrong answer in a codechef c code(codechef-STATUES)

I am trying to solve this question, but on codechef its showing wrong answer,link to the queston is http://www.codechef.com/problems/STATUES/ .On system ,its showing correct answer, after trying a lot, i couldnt find the bug My code is,
#include<stdio.h>
//#include<conio.h>
int main()
{
int a[150];
int n;
int i;
int sum;
int avg;
int count=0;
scanf("%d",&n);
int ans;
int diff;
while(n!=0)
{
sum=0;
ans=0;
count++;
for(i=0;i<n;i++)
{ scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=sum/n;
for(i=0;i<n;i++)
{ diff=avg-a[i];
if(diff>0)
ans=ans+diff;
}
printf("Set#%d\nThe minimum number of moves is %d.\n",count,ans);
scanf("%d",&n);
}
return 0;
}
Read the condition in the question:
Output a blank line after each test case.
Be careful about the case and punctuation in the above strings. Not adhering to the output format strictly will lead to the Wrong Answer verdict.
There is no blank line after your each output. Also one more for loop is needed to met the condition for exact output format. Add this snippet after while.
for(i=0;i<n;i++)
{
printf("\nSet #%d\nThe minimum number of moves is %d.\n",i,ans);
}
Another problem is
int a[150];
a should not exceed from 50. Change it to
int a[50];
But I woul advice you to use variable length array in this case to save memory.

Resources