I can't find the problem in my code, it prints only press any key to continue nothing else. I don't seem to figure out the flow of the program because of the output shown.
Help appreciated.
#include<stdio.h>
#include<stdlib.h>
int fcheck(char *name, int i, int j)
{
if (i > j)
return 1;
if (name[i] != name[j])
return 0;
else
fcheck(name, i++, j--);
return 1;
} // close fcheck
int main()
{
int c;
char name[] = "mom";
int i = 0, j = 2;
c = fcheck(name, i, j);
if (c == 1)
printf("Palindrome");
else
printf("Not a Palindrome");
return 0;
} // close main
fcheck(name,i++,j--);
only changes the values of i or j after calling fcheck. This means that you get a repeating callstack for fcheck(name,0,2) which only terminates when your stack overflows.
If you want to use recursion here, you need to use pre-increment/decrement instead
return fcheck(name,++i,--j);
Note that I've also added a return here. Without this, any string whose first and last characters match will be reported a palindrome.
1) Infinite loop problem
this line
fcheck(name,i++,j--);
should be
fcheck(name,++i,--j);
because
fcheck(name,i++,j--);
is equivalent to
fcheck(name,i,j);
i++;
j--;
so with this way of incrementation you will get an infinite loop because you are recalling fcheck() with the same arguments
and
fcheck(name,++i,--j);
is equivalent to
i++;
j--;
fcheck(name,i,j);
with this way you are not recalling fcheck() with the same arguments. So it should fix your infinite loop problem
2) should add return after the recursive call
As mentioned in the other answer, you should add return when you call the recursive function
return fcheck(name, ++i, --j);
int fcheck(char *name, int i, int j){
if (i > j)
return 1;
if (name[i] != name[j])
return 0;
return fcheck(name, i+1, j-1);
}
Related
I try to write a code that you set a password and than set a limit of tries, which is the variable mistakes, and input different string to test if my guess and my password matches
The problem is, my variable, mistake, its value changes into "0" when the program goes into the for-loop even though I didn't change it's value in the loop.
my code is below
#include <stdio.h>
#include <stdlib.h>
int main()
{
char password[6];
gets(password);
int mistake = 0;
scanf("%d\n", &mistake);
char guess[6];
int i = 0;
int k = 0;
int count = 0;
printf("%d\n", mistake);
for(i = 0; i<mistake; i++)
{
gets(guess);
printf("%d", mistake);
for(k = 0; k<6; k++)
{
if(guess[k] != password[k])
{
if(i == mistake-1){
printf("you were electrocuted\n");
return 0;
}
else{
printf("wrong password\n");
break;
}
}
else
count++;
}
if(count == 6){
printf("correct\n");
return 0;
}
}
return 0;
}
I expect the value never changes inside the loop or out side the loop, however it's value always changes into 0. I check the variable, mistake, its value before the loop and inside the loop.I want to know why it changes and what should I do. I thought about if it's the problem about gets(), but I don't see anything that works for me.
I was trying to make a program where if I enter an integer, the program would find out the bigger number and subtract it by the smaller number. This part, I got it.
The problem is, the infinite loop part.
I tried to get type in two integers keep on printing with the while loop, and break when at least one character is typed in.
For example, if I type in 2 #, it would break.
But I couldn't find the write place to get the break; within the code and therefore whenever I enter a character it would keep on creating an infinite loop.
Is there any way to create a break in this code? I humbly ask for advice...
The following is the code which I couldn't put the break
(By the way, the reason I did the condition in while as sizeof(i)==4 || sizeof(j)==4 was to make it so it would only enter an integer, since the size of an integer is 4)
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i){
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
The bottom code is the one I tried to put break but failed (it kept creating an infinite loop)...
int main()
{
int i, j;
int result;
while (sizeof(i)==4 || sizeof(j)==4){
if (sizeof(i) == 4 || sizeof(j) == 4) {
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
else
break;
}
return 0;
}
and here's a code where I got rid of the sizeof and used while(1), though there wasn't much change in the fact that the break didn't work...
int main()
{
int i, j;
int result;
while (1){
printf("type in two integers : ");
scanf("%d %d", &i, &j);
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
You can't use sizeof(i) to do run-time checks! This is a compile-time constant that, in your case (32-bit integers) will always evaluate to 4.
In order to check that two valid integers have been given, you can check the return value of the scanf function (it gives the number of fields successfully scanned):
#include <stdio.h>
int main()
{
int i, j;
int result;
while (1) {
printf("type in two integers : ");
if (scanf("%d %d", &i, &j) != 2) break; // Break here if we didn't get two integers
if (i < j) {
result = j - i;
}
else if (j < i) {
result = i - j;
}
printf("%d\n", result);
}
return 0;
}
Feel free to ask fir further clarification and/or explanation.
Drop the whole concept of endless loop with break inside if.
Make a condition for the loop based on the return value of scanf(), that is practically what it is designed for.
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
printf("type in two integers : ");
while (2==scanf("%d %d", &i, &j))
{
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
printf("%d\n", result);
printf("type in two integers : ");
}
return 0;
}
I'd probably actually use do {...} while (...) with a variable storing the return value of scanf()for being used in the loop condition. I'd consider it more elegant for not having to copy the print, but I kept it closer to your code structure.
More comments on your code:
as explained in comments, sizeof() works differently than you seem to think; it is static and does not change at runtime and hence cannot be used in a loop condition
with while (sizeof(i)==4 || sizeof(j)==4){if (sizeof(i) == 4 || sizeof(j) == 4){/* a */} else {/* b */}, b cannot ever be reached, because the conditions of while and if are identical
check the possible outcomes of the if conditions inside the loop, you are leaving the one with i==j undefined and return an uninitialised value
always init all variables as a habit
for a good MRE include the include lines
On your request, here is a proposal for the do-while alternative:
#include <stdio.h>
int main()
{
/* always init everything */
int i=0, j=0;
int result=0;
int iScanned=0;
do
{
printf("type in two integers : ");
iScanned=scanf("%d %d", &i, &j); /* keep the return value for loop */
if (i < j) {
result = j - i;
}
else /* removed second if, to have a meaningful result for i==j */
{
result = i - j;
}
if(2==iScanned) printf("%d\n", result); /* if to avoid awkward last output */
} while (2==iScanned);
return 0;
}
I am a beginner to arrays in recursion so need some guidance.
I am trying to find whether an element is present in an array or not.
// Program to find whether an element exist in an array or not.
#include <stdio.h>
int arr[5]= {1,2,3,4,5};
int fooSearch(int array1[],int N,int i, int X)
{
if(i==N)
return 0;
else if (array1[i]==X)
return 1;
else
return fooSearch(array1,N,i++,X);
}
// N denotes total size 5
// i counter that moves from 0 to 4 and eliminate recursion when it reaches 5
// X is the element to be found
int main() {
fooSearch(arr,5,0,3);
return 0;
}
The error I obtained is Segmentation Fault (SIGSEGV).
Please guide me what wrong I am doing with this code.
i++ is a post-fix increment, which increments i after the expression containing it is evaluated. Thus, every call to fooSearch effectively becomes to fooSearch(array1, N, 0, X). Recursion is endless, hence the segfault (or a stack-overflow on my compiler). (You can confirm that i is unchanging by placing printf("%d\n", i) at the top of the function.)
Fix this by using pre-fix increments, which increment the variable before evaluation.
return fooSearch(array1, N, ++i, X);
Or use i+1, since you won't be reusing the local variable anyways.
return fooSearch(array1, N, i+1, X);
While calling fooSearch() recursively pass i+1 instead of i++ as post increment i++ doesn't change i in the argument. For e.g
fooSearch(array1,N,i+1,X);
to find whether an element is present in an array or not.
you can initialize number of array elements, Let's say 10 elements:
int num[10]= {2,3,5,6,1,8,4,9,0,7};
Then, Creating for loop for checking if number 9 is not in array then continue until the condition is false then print the element location.
for(i=0; i<10; i++){
if(num[i] != 9){
continue;
}
printf("9 is found here\n%d",i);
break;
}
At the end, You write an if condition to check if the loop is ended and print not found.
if(i==10){
printf("Not Found");
}
The full code is here:
#include <stdio.h>
int num[10]={2,3,5,6,1,8,4,9,0,7};
int i;
int main(void){
for(i=0; i<10; i++){
if(num[i] != 9){
continue;
}
printf("9 is found here\n%d",i);
break;
}
if(i==10){
printf("Not Found");
}
getchar();
return 0;
}
You have to use ++i or i+1 instead of i++.
i++ is a post increment operator, so the value of i that will go to the function will not change.
Just use ++i or i+1 and you will get the answer.
public static boolean checkNumber(int input[], int x) {
int n=input.length;
if(n==0)
return false;
if(input[0]==x)
{
return true;
}
int small[]=new int[n-1];
for(int i=1;i<n;i++)
{
small[i-1]=input[i];
}
return checkNumber(small, x);
}
// Program to find whether an element exist in an array or not.
// Number of elements of array is N, the number to search is X
#include <stdio.h>
int arr[]= {1,2,3,4,5};
int fooSearch(int array1[],int N,int i, int X)
{ if(i==N)
return 0;
else if (array1[i]==X)
return 1;
else
i=i+1;
return fooSearch(array1,N,i,X);
}
int main() {
int x = fooSearch(arr,5,0,9);
printf("%d",x);
return 0;
}
In a school exercise (on paper) i've this question:
5) rewrite the code without using continue and break:
for (i = 0; i < N; i++) {
scanf("give me an int %d", & a);
if (a < 0) {
continue;
}
if (a == 0) {
break;
}
/* elaborate positive int */
}
I'm thinking about this:
for(i=0;i<N;i++){
scanf("give me an int %d",&a");
if(a==0){return -1; //??i dont know how to exit}
if(a<0){
do{
scanf("give me an int %d",&a");
if(a==0){return -1; //??i dont know how to exit}
}while(!(a<0))
}
/* elaborate positive int */
}
but, I'm actually not able to do this.. can you help me? thanks :)
Might not be what your teacher wants but that's actually the easiest way:
a = INT_MAX;
for(i = 0; i < N && a != 0; i++) {
scanf("give me an int %d", &a);
if(a > 0) {
/* elaborate positive int */
}
}
The reason for not using return is that you just want to exit/restart the loop. The function could contain more stuff that should not be skipped.
And that scanf call looks wrong.. do you really want to enter "give me an int .." everytime?
for(i = 0; i < N && a != 0; i++)
{
scanf("give me an int %d",&a");
if(a>0)
{ /*do stuff*/ }
}
if(a==0) i--; //As noted by Daniel Fischer
Not going to give you full code, but:
remember you can add conditions inside the clause of the for statement. (hint: move the breaking condition there to terminate the loop)
does the continue actually do anything in your example?
In this specific case, not much needs to be done. Since a < 0 and a == 0 are mutually exclusive conditions, an if-else-if statement could be used as follows:
for (i = 0; i < N; i++)
{
scanf("give me and int %d", &a);
if (a < 0)
// Do something or nothing here, but this skips the rest of the loop
// body just like continue would.
else if (a == 0)
i = N; // This satisfies the loop condition, so it won't loop again
// just like break would.
}
This is not a general solution, but it should give you the proper behavior in this case.
getLine is a function that gets a line, I'm trying to combine lines together outside the getLine function. When ever I try doing this in a loop it messes up the output. I bet it has to do with the pointers, but I have spend many hours trying to figure it out.
int num;
int matrix[370];
i=1;
j=0;
while(*(point=getLine(infile)) != -2){
n[j]=*point;
if(n[0] != n[j]){
printf("matrix dim error 1");
break;
}
while (i<=n[j]){
matrix[i+(3*j)] = *(point+(i+(3*j)));
i++;
printf("%d", matrix[i+(3*j)]);
}
printf("%d %d %d\n", matrix[1],matrix[2],matrix[3]);
j++;
}
fclose( infile );
}
int *getLine(FILE *infile){
int l=0;
int line[7];
int i=1;
int *point;
while ((l=getNum(infile)) != -1){
if(l==EOF){
line[0]=EOF;
point = &line[0];
return(point);
}
line[i]=l;
i++;
}
if(i==1){
line[0]=-2;
point = &line[0];
return(point);
}
line[0]=(i-1); //stores the length of the line in first space
printf("%d %d %d\n",line[1],line[2],line[3]);
point = &line[0];
printf("%d\n",*point);
return(point);
}
int getNum(FILE *infile) {
int c=0;
int value=0;
while ((c=fgetc(infile)) != '\n') {
if(c==EOF){
return(EOF);
}
if((c==32)||(c==13)){
if(value != 0){ //Making sure a number has been gotten
//printf("%d\n\n", value);
return(value);
}
//otherwise keep getting characters
}
else if ((c<=47)||(c>=58)){
printf("incorrect number input %d\n", c);
exit(1);
}
else {
value = (10*value) + (c - '0');
}
}
return(-1);//flags that the end of line has been hit
}
There is one problem:
int *getLine(FILE *infile){
int line[7];
int *point;
point = &line[0];
return(point);
}
You return a pointer to a local variable. It becomes invalid when you return from the function. You could allocate it instead on the heap, or let the caller provide it as an argument.
Instead of
while (i<=n[j]){
didn't you mean
while (i<=n[j][0]){
More Edit: That's actually ok, i overlook the * in the assignment.
Edit: Some more things:
there is no check that the range of int is not exceeded in getNum
there is no check in getLine that more than 7 values are read (which would blow int line[7]
the matrix calculation in my opinion assumes that there are 3 values read, getLine can deliver up to 7
matrix[i+(3*j)] = *(point+(i+(3*j))); ?? point is only 7 int big!!! so for the second value it will read beyond defined data. Shouldn't it read matrix[i+(3*j)] = point[i];
hth
Mario
BTW: I strongly recommend:
resort to std-lib functions
better naming (i and j in the same source are strongly discouraged)