C Program Keeps returnig 1 [closed] - c

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

Related

Write a C function that takes a number as a parameter and returns 1 if it is prime, otherwise, it returns 0. It prints 1 for 23 and 0 for 22 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I just want a 1 or 0 if it is prime or not.
but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a as input to a function that returns int eg int num(int a) or void num(), whereas OP ended up going halfway int num().
The working(if you can call it that, since fflush(stdout) is not called after printf is called, so the program will not not show the question on mingw without winpty) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
++c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
The reason you get multiple 0s and 1s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1 in this case and a 0 otherwise.
Function isprime should take an int argument and return 1 or 0, the main() function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i++) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.

Why is my CheckFactorial script not working? [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
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == factorial(number))
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac;
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
}
Why is this code not working?
My C code is meant for you to input a number and check if that number can be a factorial.
Like for example: if you enter 6 it should be Yes because 3! = 6 but if you enter 8 it would not work.
I d'ont think it's a duplicate because the method i did it was different.
Please note i'm not really good at C so any extra tips could be appreciated.
You need to correct 3 mistakes to make this program work.
You're comparing factorial of whichnumber with factorial of number that's wrong.
currnumber = factorial(whichnumber);
if (currnumber == factorial(number)) //<----never be true
{
return 1;
}
You should compare factorial of whichnumber with number
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
2 . You should initialize fac variable in factorial function otherwise it will take some garbage value.
int fac=1; //<-----initialize this variable
3. You should return the value of fact after calculating the factorial.
return fac; //<-----should return value
Here is the modified code:
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac=1; //<-----initialize this variable
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
return fac; //<-----should return value
}
It has been pointed out to you that you don't return value from your functions and use uninitialsed values. These errors are easy to make, but they are also easy to catch: Enable warnings for your compiler and they will tell you about these things.
Suvojit's answer tells you what is wrong with your factorial function. Unfortunately, more things are wrong with your factorial check:
You make the number you check a global variable. This should really be an argument to the function, so that you can call it like you should: is_factorial(n).
You make your counter a static variable. This is like a global variable, but with the restriction that it is only known in this function, which means that you cannot change it from outside. If your program want to check several numbers, the second call starts where you left off earlier, which leads to wrong results.
Of course that's what you want in your implementation, because you use a recursive algorithm. In this case, that's not a good choice; use a loop.
Your condition when to stop the iteration (or when to break the loop) checks the number against the number you took the factorial of. You should test this against the factorial itself.
Note that a typical int has 32 bits and can represent positive values up to 2³¹. The factorial 13! already exceeds this limit. So you must check your number against 12 values.
You don't need the factorial function for this, you can build these values as you go, because n! = (n − 1)! · n. (You can use the factorial function, but will do the same calculations over and over again, which is wasteful. It doesn't matter for this toy problem, but it is worth bearing such things in mind.)
So here's your function, completely rewritten:
int is_factorial(int n)
{
int fact = 1;
int k = 1;
while (k < 13 && fact <= n) {
fact *= k;
if (n == fact) return k;
k++;
}
return 0;
}
It returns 0 when the n isn't a factorial, otherwise it returns the number that n is a factorial of. (This information is used anyway, so why not provide it? The caller can choose whether to use this infor or just use it as truth value.)
While we're at it, let's adjust the main function so that the program checks for bad input and prints out the extra information we return:
int main(void)
{
int n;
printf("Enter a number: ");
if (scanf("%d", &n) < 1) {
printf("Illegal input!\n");
} else {
int m = is_factorial(n);
if (m) {
printf("%d is the factorial of %d!\n", n, m);
} else {
printf("%d is not a factorial!\n", n);
}
}
return 0;
}
The things to take away here are that you should use the compiler warning to tell you about simple errors, that you should avoid global and static variables for closed problems like these and that loops are often simpler than recursion.

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.

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.

Program stops and does nothing for no reason [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 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.

Resources