Program stops and does nothing for no reason [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Here is my code. It will take the info from the user fine, but it doesn't call prims! (it doesn't even print the statement before the call..). The issue is, this main() is simply copy-and-pasted from an attempt at this problem using kruskals instead of prims.. the main is unchanged, and it used to work fine, the only difference is prims() is now there. I can't see any reason why the program would just.. stop (and then does nothing. Blinking cursor nothing). What's going on?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 50
typedef struct graph{
int vertices;
int edges;
int vertex[MAX];
int edge[MAX][4]; /*[i][0]=i (edge ref) [i][1]=vertex1 [i][2]=vertex2 [i][3]=weight*/
} Graph;
void prims(Graph graph);
int main () {
Graph* graph=malloc(sizeof *graph);
printf("Please enter the number of vertices in your graph: ");
scanf("%i", &graph->vertices);
printf("\nPlease enter the number of edges in your graph: ");
scanf("%i", &graph->edges);
for (int i=0; i<graph->edges; ++i) {
graph->edge[i][0]=i;
ensure_valid_input:
printf("\nPlease enter the vertices connected by edge %i, and its weight: ",i+1);
scanf("%i %i %i", &graph->edge[i][1], &graph->edge[i][2], &graph->edge[i][3]);
if (graph->edge[i][1]>graph->vertices || graph->edge[i][2]>graph->vertices || graph->edge[i][1] <= 0 || graph->edge[i][2] <= 0) {
printf("\nERROR: One of these vertices is invalid; ensure they are both in range 1 - %d\n", graph->vertices);
goto ensure_valid_input;
}
}
printf("Try to call the function?");
prims(*graph);
/*Print result to screen*/
/*Print result to file*/
return 0;
}
void prims(Graph graph){
printf("Function called...");
/*Initialise sets and test-values*/
int edges_ordered[graph.edges];
int used_vertices[graph.vertices];
int used_edges[graph.vertices-1];
int least_avail_edge;
int least_edge_reset;
int existing_entry;
int done=1;
int vertex_present;
for (int i=0; i<graph.vertices; ++i) {
if (i=0) {
used_vertices[i]=0;
}
else {
used_vertices[i]=-1;
}
}
/*Order the edges*/
for (int i=0; i<graph.edges; ++i) {
least_avail_edge = least_edge_reset;
existing_entry = 1;
for (int j=0; j<graph.edges; ++j) {
if (graph.edge[j][3]<=graph.edge[least_avail_edge][3]) {
for (int k=0; k<graph.edges; ++k) {
if (edges_ordered[k]==graph.edge[j][0]) {
existing_entry=0;
}
}
if (existing_entry==1) {
least_avail_edge=j;
}
}
}
edges_ordered[i]=least_avail_edge;
}
//Diagnotstic Print
for (int i=0; i<graph.edges; ++i) {
printf("\n%d) Edge %d, Weight %d\n)", i+1, edges_ordered[i]+1, graph.edge[i][3]);
}
/*Continually add next appropriate edge to tree until spanning*/
while (done!=0) {
/*Test to see if all vertices are in the tree yet*/
done=0;
for (int i=0; i<graph.vertices; ++i) {
vertex_present=1;
for (int j=0; j<graph.vertices; ++j) {
if (graph.vertex[i]==used_vertices[j]) {
vertex_present=0;
}
}
if (vertex_present==1) {
/*Vertex is missing from tree -- not done!*/
done=1;
break;
}
}
}
}

There are a lot of problems with this code, but I suspect the culprit is inside your prims() function:
if (i=0) {
I think you mean ==. You're setting i to zero each time through the loop, which causes the loop to never terminate, freezing your program.
Other problems are that least_edge_reset is uninitialized, the return value of malloc is not cast (depends on the C/C++ version and compiler settings whether you'll get an error or warning for this), and sizeof *graph is awkward. Also there's no protection against exceeding the maximum number of edges, etc. etc., but I'll stop there since it's not what you were asking about.
I suspect your print statement IS running, but since there is no \n, it is being buffered and not displayed on screen right away, and never gets displayed because prims() is stuck in an infinite loop.

Related

Why array doesn't print correct numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Following code:
#include <stdio.h>
int izbaciSveProste(int n, int x[], int y[])
{
int i;
int flag=0;
for(i=2; i<n/2; i++)
{
if(n%i ==0)
{
flag =1;
break;
}
}
if(flag==1)
return 0;
else
return 1;
}
int main()
{
int i,j,n,x[100],y[100];
printf("Koliko elemenata zelite u polju?\n");
scanf("%d", &n);
printf("Enter elements in array:- ");
for(i=0;i<n;i++)
{
scanf("%d",&x[i]);
}
int len = sizeof(x)/sizeof(x[0]);
for(i=0; i<len; i++)
{
if(izbaciSveProste(x[i]))
{
for(j=i; j<len; j++)
{
x[j] = x[j+1];
}
i--;
len--;
}
}
printf("Elementi nakon brisanja su:\n");
for(i=0; i<len; i++)
printf("%d\n",y[i]);
printf("\n");
return 0;
}
Purpose of this program should be to delete all prime numbers from array x[] with n elements, remaining elements should be rewritten in array y[] and show count of elements in array y[] in the end.I believe that function is okay and error is in main() specifically in storing y[].
Your function int izbaciSveProste(int n, int x[], int y[]) requires three arguments. Your code izbaciSveProste(x[i] passes one argument. That's not much enough. The compiler tells you that fact with the error message:
error: too few arguments to function 'izbaciSveProste'
Your function prototype has 3 parameters:
int izbaciSveProste(int n, int x[], int y[])
When you call the function, you only provide 1:
if(izbaciSveProste(x[i]))
The compiler wants to get all 3.
As your function doesn't even touch the 2 array parameters, you might simply remove them from the function definition and only take 1 integer.
Another problem:
You print y[i] in your loop but you never assign any value to that array.

C Program Keeps returnig 1 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing this code:
#include <stdio.h>
int main()
{
int t[50],n,i,test=1;
printf("Donner la Taille N du tableau :");scanf("%d",&n);
for(i=0;i<n;i++,scanf("%d",&t[i]));
for(i=0;i<n-1;i++)
{
if(t[i]>t[i+1]){test=0;break;};
};
return test != 0);
}
it is supposed to return 1 if the array is ascending but it always return 1
for(i=0;i<n;i++,scanf("%d",&t[i]));
^^^ ^^^
That increments i before scanf runs... Do instead
for(i=0;i<n;i++) {
scanf("%d",&t[i])
}
The for loop
for(INIT ; COND ; INCREMENT) ACTION;
is equivalent to
INIT;
while (COND) {
ACTION;
INCREMENT;
}
In your program, the actual action was part of INCREMENT, and done after i++ (commas separated statements are evaluated and executed from left to right), the 0 value was skipped, and moreover t[n] was written to, n being logically out of bounds (since it is not a problem while n is <=49).
Note that INIT and INCREMENT are conventions, since you may do a lot of things there that are neither initializations, nor increments! - as you did actually
Below, a version that use only one loop, no array and less variables, followed with explanations
#include <stdio.h>
#include <limits.h>
int main(){
int n,v,previous = INT_MIN; // INT_MIN: minimal int value
printf("Donner N le nombre de valeurs :");
scanf("%d",&n);
while (n-- > 0) {
scanf("%d", &v);
if (v < previous) return 0;
previous = v;
}
return 1;
}
Explanations
previous is assigned the lowest possible integer value
while (n-- > 0) ensure n is initially > 0, will loop n times
read a value v, if v < previous that means the sequence is not ascending
return directly 1 or 0
Bon courage :-)
Don't take it prsonally, but this code is ugly. If you put effort into writing nicer code, it will be much easier to read it and to find errors in it.
I would suggest this:
#include <stdio.h>
int main() {
int t[50];
int n;
int i;
int test=1;
printf("Donner la Taille N du tableau:");
scanf("%d", &n);
// here you will want to make sure that n <= 50!
for(i=0; i<n; i++) {
scanf("%d", &t[i]);
}
for(i=0; i<n-1; i++) {
if(t[i] > t[i+1]) {
test=0;
break;
}
}
return test != 0;
}
Ad the bug should already be fixed ;)

3 Highest Numbers in an array without sorting, Where am I missing the logic? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
This program is for finding 3 highest numbers in an array.
When I run the code, I'm getting first highest and second highest. And second highest is getting repeated for third number
What am I missing in the logic?
#include<stdio.h>
#include<conio.h>
int main()
{
int i,k,n,m[20],h[3];
printf("\n enter the total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the marks scored by student %d",i+1);
scanf("%d",&m[i]);
}//end for loop
k=0;
h[k]=m[0];
for(i=0;i<n;i++)
{
if(m[i]>h[k])
{
h[k]=m[i];
}
}//end for loop
do
{
//Probably messed my code here
k++;
h[k]=m[0];
for(i=0;i<n;i++)
{
if(m[i]>=h[k-1])
{
if(m[i]>h[k])
{
h[k]=m[i];
}//end if
break;
}//end if
}//end for loop
}//end do loop
while(k<3);
printf("the first 3 highest marks are:\n");
for(i=0;i<k;i++)
printf("%d:%d\n",i+1,h[i]);
getch();
}//end of main
I don't know, what is your purpose behind writing such a hugh lines of code if this can be done in much simpler way.
Here is another approach of finding Top 3 numbers in just one iteration;
Hope you may like it and it might help you in future.
SOURCE:
#include<stdio.h>
#include<limits.h>
int main()
{
int a[10] = {5,4,3,6,7,8,9,10,1,2};
int h1 = INT_MIN; //TOP 1st
int h2 = INT_MIN; //TOP 2nd
int h3 = INT_MIN; //TOP 3rd
for(int i=0;i<10;i++)
{
if(a[i] > h1)
{
h3 = h2; h2 = h1; h1 = a[i];
}
else if (a[i] > h2)
{
h3 = h2; h2 = a[i];
}
else if (a[i] > h3)
{
h3 = a[i];
}
}
printf("TOP 1st is<%d>\n",h1);
printf("TOP 2nd is<%d>\n",h2);
printf("TOP 3rd is<%d>\n",h3);
return 0;
}
OUTPUT:
./a.out
TOP 1st is<10>
TOP 2nd is<9>
TOP 3rd is<8>
I see the following problems:
The line
h[k]=m[0];
will lead to problems if m[0] is the largest or the second largest value. Change it to:
h[k]=INT_MIN;
The line
if(m[i]>=h[k-1])
seems wrong. That should be
if(m[i] < h[k-1])
The line
break;
is a source of error. It will fail to detect the second and third largest values correctly if they are towards the end of the list.
Here's the do/while block with those fixes.
do
{
k++;
h[k]=INT_MIN;
for(i=0;i<n;i++)
{
if(m[i] < h[k-1])
{
if(m[i]>h[k])
{
h[k]=m[i];
}//end if
}//end if
}//end for loop
}//end do loop
It seems to work for me.
One of your problems is with the line
if(m[i]>=h[k-1])
This condition is going to be met once per iteration of your do...while loop (assuming the highest mark occurs just once), and the next line is going to be executed only if the highest number is not the first one.
It's not the only problem with the code. There are lots of conditions under which this code isn't going to work right, alluded to by Nitin Tripathi's comments.
I suggest you load the h array with the first three marks. Then, sort it using a bubble-sort algorithm so that h[0] is the highest and h[2] is the lowest. Then iterate over the remaining values of the marks. For each value, if it is higher than h[2], replace h[2] with it and re-sort the h array using the same bubble-sort algorithm. You can just google that and find lots of examples.
Commenting your code would probably help you a lot, as well.
You need to sort h array, following code working fine
#include<stdio.h>
#include<conio.h>
void main()
{
int i,a,j,k,n,m[20],h[3];
int high, temp;
printf("\n enter the total number of students");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the marks scored by student %d",i+1);
scanf("%d",&m[i]);
}//end for loop
k=0;
h[k]=m[0];
for(i = 1; i < n; i++)
{
if(m[i] > h[0])
{
h[k] = m[i];
k++;
// make sure h[0] have max value out of all 3
for (a = 0; a < k; a++)
{
for (j = a + 1; j < k; j++)
{
if (h[a] < h[j])
{
temp = h[j];
h[j] = h[a];
h[a] = temp;
}
}
}
}
}//end for loop
for (i = 0; i < k; i++)
{
printf("\n %d", h[i]);
}
getch();
}
#include <algorithm>
#include <cstddef>
template<typename RanIt>
void make_N_highest( std::size_t N, RanIt b, RanIt e )
{
std::make_heap(b,e);
while(N--)
std::pop_heap(b,e--);
}
This will put the N highest values last in the sequence.
It's O( N * log(size) )

Binary search in C language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
What is the problem with the next code ?
It is a code for making a binary search between the elements of an array that we fill randomly using the rand() function. We use here the function bin_sear to sort and return for us a boolean value true if the element we seek is found in our table and flase if the element we dont find doesent figure in our table. The code doesent work. So where is the error here ?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef enum { false, true } bool;
bool bin_sear(int k[] ,int s , int target );
int main()
{
int a[10];
int i,j;
char k;
bool bin;
while(1){
srand(time(NULL));
// we fill our table
for(i=0;i<10;i++){
a[i]=rand()%101+1;
}
printf("Please enter the element you are seeking for: ");
scanf("%d",&j);
if(bin_sear(a[10],10,j)==true){
printf("The element you seek exists in our array");
}
else {
printf("The element you are seeking doesent exist in our array");
}
if (k=='n'){
break;
}
}
return 0;
}
bool bin_sear(int k[],int s, int target){
int i,j,pos,aux,low,high,test;
for (i=0;i<s;i++){
pos=i;
for (j=i;j<s;j++){
if (k[j]<pos){
pos=j;
}
aux=k[pos];
k[pos]=k[i];
k[i]=aux;
}
}
low=0;
high=s;
while (low<high-1){
test=(low+high)/2;
if (target<k[test]){
high=test;
}
else low=test;
}
if (target==k[test]){
return true;
}
else return false;
}
A number of errors in your code.
You need to call bin_sear with the pointer to the array, not element a[10] (which will give you an immediate segmentation fault):
if(bin_sear(a[10],10,j)==true){
should be
if(bin_sear(a,10,j)==true){
Next - take a look at your bubble sort routine. You have the indices wrong, and the braces in the wrong place, and you are comparing a value to an index with your if statement. Modify it to this, and you will get a sorted array:
for (i=0;i<s-1;i++){
pos=i;
for (j=i+1;j<s;j++){
if (k[j]<k[i]){
pos=j;
aux=k[pos];
k[pos]=k[i];
k[i]=aux;
}
}
}
Next, you don't seem to set the value of k anywhere, so you have an infinite loop. Fix all that, and things will work a little bit better. Recommend you put a lot of printf statements in your code if this is not enough (and use a smaller range of random numbers initially to improve your chances of a hit).
Working code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef enum { false, true } bool;
bool bin_sear(int k[] ,int s , int target );
int main()
{
int a[10];
int i,j;
char k;
bool bin;
while(1){
srand(time(NULL));
// we fill our table
for(i=0;i<10;i++){
a[i]=rand()%10+1;
}
printf("Please enter the element you are seeking for: \n");
// scanf("%d", &j); // not scanning input since this is codepad
j = 5;
printf("you entered: %d\n", j);
fflush(stdout);
if(bin_sear(a,10,j)==true){
printf("The element [%d] exists in our array\n", j);
}
else {
printf("The element [%d] doesn't exist in our array\n", j);
printf("The array contains:\n");
for(i = 0; i < 9; i++) printf("%d, ", a[i]);
printf("%d\n", a[9]);
}
printf("Would you like to test for another element?\n");
// k = getchar();
k = 'N'; // simulating user pressing uppercase N
if(tolower(k) == 'n') {
printf("goodbye!\n");
break; // do this only once
}
}
return 0;
}
bool bin_sear(int k[],int s, int target){
int i,j,pos,aux,low,high,test;
printf("starting to sort\n");
fflush(stdout);
for (i=0;i<s-1;i++){
pos=i;
for (j=i+1;j<s;j++){
if (k[j]<k[i]){
printf("swapping %d and %d\n", i, j); fflush(stdout);
pos=j;
aux=k[pos];
k[pos]=k[i];
k[i]=aux;
}
}
}
printf("sort finished\n");
printf("elements now:\n");
for(i = 0; i < s; i++) printf("k[%d] = %d\n", i, k[i]);
fflush(stdout);
low=0;
high=s;
while (low<high-1){
test=(low+high)/2;
if (target<k[test]){
high=test;
}
else low=test;
}
if (target==k[test]){
return true;
}
else return false;
}
if(bin_sear(a[10],10,j)==true){ => if(bin_sea(a, 10, j) == true) from a quick glance. You need to pass the array into the function, a[10] would try to index the eleventh elment of the array, is also the wrong type (being an int instead of an array), and will probably cause an access violation exception, because the array is only ten elements long. Lots of errors for four characters, eh?
It makes no sense to write a function which sorts the array and then makes the binary search. You should separate the two algorithms, otherwise a linear search would be more efficient.

array that accepts a number only once(code doesn't work) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to make an array that accepts each number just once and if the user tries to insert a number more than once,then he must enter an other number...can anyone help me please?
I have tried this so far:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a[5];
int i,j,num;
scanf("%d",&num);
a[0]=num;
for(i=1;i<5;++i){
again: scanf("%d",&num);
if(a[i]!=a[i-1])
a[i]=num;
else
goto again;
}
for(i=0;i<5;i++)
printf("%4d\n",a[i]);
system("pause");
return 0;
}
but the code just doesn't work and i don't know why
it is observed from your code that given array must be filled but it should not contain redundant values.
following code iterates until the array is filled with no redundant value, once the array is filled it terminates.
int a[5],i=1,k=0,p;
int num;
scanf("%d",&num);
a[0]=num;
while(i<5)
{
scanf("%d",&num);
for(p=0;p<=k;p++)
{
if(a[p]==num)
{
break;
}
if(p==(k))
{
a[i]=num;
k=i;
i++;
}
}
}
for(i=0;i<5;i++)
{
printf("%d",a[i]);
}
hope this could help you
You are just comparing the new entered value with the previous one in a[i]!=a[i-1].
You better create a function to test the new value with the entire array, like
int valueExists(int num, int a[], int len) {
int i;
for (i = 0; i < len; i++) {
if (a[i] == num) {
return 1;
}
}
return 0;
}
Make sure you adding the new value to the array only after testing the value is not there.
again: scanf("%d",&num);
if (valueExists(num, a, i)) {
goto again;
} else {
a[i] = num;
}
(The loop you created with the goto can be replaced by a do-while loop, but that is not the issue here)

Resources