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

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

Related

Keep getting the same answer when writing a recursive function

Note: I'm fairly new to C programming so I don't know everything just yet.
So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.
This is what my code is:
#include <stdio.h>
int count_digits(int num)
{
static int count=0;
if(num>0)
{
count++;
count_digits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
printf("Enter any number:");
scanf("%d",&number);
count=count_digits(number);
printf("\nTotal digits in [%d] are: %d\n",number,count);
return 0;
}
Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:
return count_digits(num/10);
there are a few things to consider:
What happens if you call your function count_digit() more than one time in the program?
What if you enter 0, 10, 100 as number?
Perhaps you should rethink using a static variable here.
Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

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++ )

Error while printing sorting array in C language?

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.

Why does the program crash when the function is called in c?

I recently had to create a program where the user enters a certain integer N. After that, my int main() had to call a seperate function, int getNextFibonacciNumber(void), which calculates the Nth term in the fibonacci sequence and then prints it. When I compile the code, Vode::Blocks says that there aren't any errors or warnings. This said, when I try to run the program, it automatically crashes. I have read it and re-read it but I am not able to see where it all went wrong. Would anyone be able to shed some light on this mysery? Thank you very much! When the program crashes, it says: filename.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solutions is available. However, when the code is compiled in Code::Blocks, everything is fine.
#include <stdio.h>
#include <stdlib.h>
int getNextFibonacciNumber(void);
int main()
{
int N, fibonacci[N];
printf("Enter a positive integer:");
scanf("%d", &N);
printf("The %d th term in the Fibonacci sequence is: %d", N, getNextFibonacciNumber());
}
int getNextFibonacciNumber()
{
int N, i, fibonacci[N];
fibonacci[0] = 0;
fibonacci[1] = 1;
for(i = 2; i < N+1; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return(fibonacci[N-1]);
}
The problem is, that this
int main()
{
int N, fibonacci[N];
invokes undefined behavior. N is not initialized, but used as a C99 variable length array size specifier. Reading a value from a uninitialized variable invokes UB.
To fix this issue you have to write
int main()
{
int N;
printf("Enter a positive integer:");
scanf("%d", &N);
int fibonacci[N];
However there's another problem, namely that you have the same UB causing construct in getNextFibonacciNumber. You have to fix that to. Also the number entered into N is not "communicated" to getNextFibonacciNumber, so I highly doubt that this program worked at all, even if it didn't crash.
Code::Blocks (or rather the compiler Code::Blocks calls) only checks if you have written "legal" c code. It does not (and can not) check if your program does what you want, if your program will exit at any point (or simply run forever), if your program causes errors and crashs and stuff like this.
When you say
int N, fibonacci[N];
I guess you want to create an integer N and an array of the same size. However right now you create an integer N (that has some "random" value, presumably 0) and an array of the FIXED size N.
If you change N late on in your program this does not affect the size of your array "fibonacci" in any way. So if your N was by chance 0 at the beginning of your program than you have created an array of size 0. Even if you read a value (say 5) from the console input. Trying to read and write to this array causes problems.
Moving the part
int fibonacci[N];
below your "scanf" line will fix this problem. At this point N is initialized (and not some random number).
Also be aware that the variable N in the main function
int main()
has no connection at all to the N variable in your function
int getNextFibonacciNumber()
The second N is a newly created variable (again set to some "random" value). If you want to pass data from one function to another you should do it by passing it as an argument in brackets:
int getNextFibonacciNumber( int N)

How do I pass an array(1D) to a function using pointers in C?

I am struggling with the last bit of this program, I need to pass the array to two different functions and I can't figure out how to do it.
The only errors I get occur:
Here:
input(array[20]);
calculate(array[20],&pairs);
and here:
//exit,
exit;
Other than that it should work the way I need it to, I figured out how to use pointers on normal variables but the arrays act differently and I can't figure out what to do...
The documentation is half done and I still have to add the loop at the end that the description outlines, but I just need help with passing the arrays.
Also the error involving my exit line is irrelevant to the question, but if you know a fix that would be great!
/*
Description: Do not use global variables. Pass your arguments by value and
by reference. Using arrays and modular programming techniques,
write a C program that will allow a user to populate an array
with integers, and then compute and print out the number of
adjacent pairs in the array (i.e. the number of occurrences where
an array element is the same as its neighbors). For example, if
the array contained [2,3,3,4,52,52,4,4,4,4,7,7,1], the number of
adjacent pairs is 6. The program should give the user the option
of examining more than one array (i.e. loop). Assume the array has
a max. of 20 elements. The main() function should primarily be
responsible to direct the flow of logic. That is: use one
function to obtain input (pass by reference), another function to
do processing (pass by value), and perhaps a third function to do
output (pass by value). The main() function should call the input
function and the processing function.
*/
//Include statements.
#include <cstdlib>
#include <iostream>
#include <math.h>
//Standard namespace.
using namespace std;
void input (int array[20]); //Used when user inputs the numbers.
void calculate(int array[20], int *pairs); //Used to calculate the matches.
void output(int *pairs); //Used to output the number of pairs.
int main(void)
{
int array[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
char quit;
start:
int pairs = 0;
input(array[20]);
calculate(array[20],&pairs);
output(&pairs);
//Ask the user if they want to exit
printf("\nWould you like to continue testing my project, or exit?");
printf("\nTo exit input: 'N' or 'n'. To continue testing input anything else.");
//store their input in variable: exit
scanf("%s",&quit);
//If they want to exit...
if (quit == 'N' || quit == 'n')
{
//exit,
exit;
}
//otherwise,
else
{
//clear the screen
system("cls");
//and go back to the start.
goto start;
}
}
void input(int array[20])
{
int count = 0;
for (count;count<20;count++)
{
printf("Enter values . . . \n");
scanf("%i", &array[count]);
}
}
void calculate(int array[20], int *pairs)
{
int counter = 0;
for (counter;counter<19;counter++)
{
if (array[counter] == array[counter+1])
*pairs+=1;
}
}
void output(int *pairs)
{
printf("Number of pairs: [%i]\n", *pairs);
}
You don't pass in a size when you're calling the function.
input(array);
That should be enough.
Another solution would be to make the function take an int*. You would add an extra parameter to pass in the size of the array.
void func(int* my_array, int size);
You would declare your array like so:
int i[20];
And call your function like this:
func(i, 20);
Currently, by passing in array[20], you're returning an int and you'd be going out of bounds in case you wanted to know since the max index is 19. The inappropriate return type of the expression is not allowing you to compile the program.

Resources