Function recursively runs forever if value above 3 is input - c

As a mandatory preface, I am new to C, and am likely simply missing something extremely obvious. I appreciate any and all time and effort taken to look over my silly problem.
I have a recursive function whose purpose is to print out a large "x" made of smaller x characters, where width is the length of each side of the x. For example, a width of "3" would have the following output:
Shape:
X X
X
X X
Returning.
Where "Returning." prints just before returning to main.
The following function does just this for a width of 1 and 3, but fails to do so with 5, 7, 9, etc.
void Recurse(int left, int right, int flag, int num){
int i;
if(((left && right) == num/2) && (flag == 0)){
for(i=0;i<num;i++){
if (i == (num/2) ){
printf("X");
}
else
printf(" ");
}
printf("\n");
flag = 1;
Recurse(left-1, right+1, flag, num);
}
else if(flag == 0){
for(i=0;i<num;i++){
if((i == left) || (i == right)){
printf("X");
}
else
printf(" ");
}
printf("\n");
Recurse(left+1, right-1, flag, num);
}
else if(flag == 1){
for(i=0;i<num;i++){
if((i == left) || (i == right)){
printf("X");
}
else
printf(" ");
}
printf("\n");
if (((left == 0) && (right == num-1)) && (flag == 1))
printf("\nReturning.\n");
return;
Recurse(left-1, right+1, flag, num);
}
}
The only thing I have in my main function is an initialization of width with some odd int, and a call to the function. I would like to get the code actually... printing correctly prior to cleaning up the logic a bit. Thank you for any help provided.

In
if(((left && right) == num/2) && (flag == 0)){
left && right is a boolean value, probably you wanted
if ((left == num/2) && (right == num/2) && (flag == 0)){

Related

Rock Paper .. game

This code runs just fine.
but there is some minor mistake in the program. I don't know what's the problem 'cause it's like I keep on winning the game and the computer just loses the game every time. 3
the game Rock, Paper, Scissors. My problem is if I execute the program, I just keep winning.I need the game to let the computer win. How can I rectify this?
#include <stdio.h
#include <time.h>
int Random(int n) {
srand(time(NULL));
printf("%d\n", rand() % 3); }
int greater(char ch1, char ch2) {
if (ch1 == ch2)
{
return -1;
}
else if ((ch1 == 'R') && (ch2 == 's'))
{
return 1;
}
else if ((ch2 == 'R') && (ch1 == 's'))
{
return 0;
}
else if ((ch1 == 's') && (ch2 == 'p'))
{
return 1;
}
else if ((ch2 == 's') && (ch1 == 'p'))
{
return 0;
}
else if ((ch1 == 'p') && (ch2 == 'r'))
{
return 1;
}
else if ((ch2 == 'p') && (ch1 == 'r'))
{
return 0;
}
}
int main() {
char playerchar, computerchar, a;
int playerscore = 0, compscore = 0, b;
char ch[] = {'R', 'P', 'S'};
printf("\n");
printf("~~~~~Welcome to the Rock, Paper, Scissors Game~~~~~\n\n");
printf("Choose a number\n 1. for Rock\n 2. for Paper\n 3. for Scissiors\n");
for (int i = 0; i < 3; i++)
{
printf("Player's Turn :\n");
scanf("%d", &b);
getchar();
playerchar = ch[b - 1];
printf("You chose %c\n", playerchar);
printf("Computer's Turn :\n");
b = Random(3) + 1;
computerchar = ch[b - 1];
printf("Computer chose %c\n", computerchar);
if ((greater(computerchar, playerchar) == 1))
{
compscore += 1;
printf("Computer got it!\n\n");
}
else if ((greater(computerchar, playerchar) == -1))
{
compscore += 1;
playerscore += 1;
printf("It's a draw\n");
}
else
{
playerscore += 1;
printf("You got it!\n\n");
}
printf("You : %d\nComputer: %d\n\n",playerscore,compscore);
}
if (compscore > playerscore)
{
printf("Computer win the game!\n\n");
}
else if (playerscore > compscore)
{
printf("You win the game!\n\n");
}
else
{
printf("The game is draw\n");
}
return 0;}
There's really no point complex if statements for determining the winner. Just realize that rock paper scissors is basically just a directed cycle graph.
// Returns winner in rock paper scissors
// 0 - Rock, 1 - Paper, 2 - Scissors
// Return values:
// 0 - draw
// 1 - a win, b loose
// -1 - b win, a loose
int rps(int a, int b) {
if(a == b) return 0;
return (a+1) % 3 == b ? -1 : 1;
}
Normal rps (rock, paper, scissors) has 3 nodes in the graph. This can actually easily be generalized to n nodes. The algorithm works like this. Start on node a. If it's the same as b, then it's a draw. Otherwise, check how many steps it is required to to go around the graph to get to b and determine the winner depending on if the number of steps is even or odd.
int rpsn(int a, int b, int n) {
if(a == b) return 0;
int steps = 0;
while((a+steps) % n != b) steps++;
return steps % 2 ? -1 : 1;
}
Read about Rock, Paper, Scissors, Lizard, Spock for a 5 node version.
I'm fairly confident that the loop could be exchanged for a single clever math operation, but I'm having a brain freeze at the moment. I'll update the post if I find it.
EDIT:
I found a way. Here is a very short rps function with no loops for arbitrary n:
// Returns the number of steps required to go from a to b
int steps(int a, int b, int n) {
return (n+b-a) % n;
}
int rpsn(int a, int b, int n) {
if(a == b) return 0;
return steps(a,b,n) % 2 ? -1 : 1;
}
The reason for doing (n+b-a) % n instead of (b-a) % n is that we need the left operand of % to be nonnegative.
First of all, srand should be called just once at the beginning of the program. You call it on every call of Random().
But the bigger issue is that your function Random() does not return anything, it just prints the value. This should have grnerated a warning in your compiler. This probably means that Random always returns 0.
To fix the problem, do return rand() % 3; instead of printing it.

comparing an inputted string to a printed function

Below is a code I wrote for a dice game called cho han. To input your guess I've used number to represent the words 'odd' and 'even'. Since then I have tried to write it again, but to actually write odd or even in the scanf section, but can't get it to work. Any help would be appreciated :)
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter '1'. To guess even, enter '2'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
scanf_s("%d", &guess);
if (guess == 2)
{
printf("\nyour guess is even.\n");
}
if (guess == 1)
{
printf("\nyour guess is odd.\n");
}
if (guess > 2 || guess < 1)
{
printf("\nInvalid guess.\nYou lose!\n");
return (1);
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
result = x + y;
printf("\ncombined total of both rolls is %d", result);
if (result == 1 || result == 3 || result == 5 || result == 7 || result == 9 || result == 11)
{
printf("\ncombined total of both rolls is odd.\n");
}
else
{
printf("\ncombined total of both rolls is even.\n");
}
if (guess == 1 && result == 1 || guess == 1 && result == 3 || guess == 1 && result == 5 || guess == 1 && result == 7 || guess == 1 && result == 9 || guess == 1 && result == 11)
{
printf("\nYou win!\n");
}
else if (guess == 2 && result == 2 || guess == 2 && result == 4 || guess == 2 && result == 6 || guess == 2 && result == 8 || guess == 2 && result == 10 || guess == 2 && result == 12)
{
printf("\nYou win!\n");
}
else
{
printf("\nYou lose!\n");
}
return 0;
}
You should change scanf_s to scanf
The line if (result == 1 || result == 3 ... could be if (result % 2 == 1) {
You could use strcmp to solve your question
The following code could work:
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
char buf[10];
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter 'odd'. To guess even, enter 'even'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
fgets(buf, sizeof buf, stdin);
if (strcmp(buf, "even\n") == 0) {
guess = 2;
printf("\nyour guess is even.\n");
} else if (strcmp(buf, "odd\n") == 0) {
guess = 1;
printf("\nyour guess is odd.\n");
} else {
printf("\nInvalid guess.\nYou lose!\n");
return 1;
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
printf("\ncombined total of both rolls is %d", x + y);
result = (x + y) % 2;
if (result == 1)
printf("\ncombined total of both rolls is odd.\n");
else
printf("\ncombined total of both rolls is even.\n");
if (guess == result)
printf("\nYou win!\n");
else
printf("\nYou lose!\n");
return 0;
}
You need to change your guess to char type and scanf to capture string.
char guess[256];
scanf("%s", guess);
And then the best way would be to call toupper() and compare with your text using strcmp().

My number converter(decimal to base 2-16) prints numbers in opposite order

I've been working on a program that, when executed, asks for two numbers, the first being any decimal number, the second number being the base (2-16) which you wish to convert to. It works great, except one thing. Every output is backwards. Which is to be expected, it takes remainders and outputs them in the order they are calculated. However I want them to come out in the opposite order. I was thinking about setting up a loop and having the remainders stored in an array, then loop through the array backwards and spit out the information. But I'm new to C and i cannot get it to work! Tell me what you think!
Any help would be very appreciated. I've been stuck on this for a while.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int x, y, z, c; //Sets up variables to be used in program
printf("Please enter two integers: "); //Asks for user input
scanf("%d", &x);
scanf("%d", &y); //stores input
printf("%d\n", x);
printf("%d\n", y);
printf(" \n");
if(y < 2 || y > 16){
printf("You have entered incorrect information.\n");
return 0;
} //bug checks
else if(y > 1 && y < 17){
while(x != 0){
c = (x%y);
x = (x/y); // Loops numbers until a 0 value is reached, can be used with
// any Base
if( c == 10){
c = printf("A");
}else if( c == 11){
c = printf("B");
}else if( c == 12){
c = printf("C");
}else if( c == 13){
c = printf("D");
}else if( c == 14){
c = printf("E");
}else if( c == 15){
c = printf("F");
}else{
printf("%d", c);
}
// Returns for each remainer option
}
printf("\n");
}
// Returns for each remainer option
printf("\n");
}
Declare
int i = 0;
int rev[50];
and change your code as
if( c == 10){
rev[i++] = 'A' ;
}else if( c == 11){
rev[i++] = 'B' ;
}else if( c == 12){
rev[i++] = 'C' ;
}else if( c == 13){
rev[i++] = 'D' ;
}else if( c == 14){
rev[i++] = 'E' ;
}else if( c == 15){
rev[i++] = 'F' ;
}else{
rev[i++] = 48 + c;
}
// Returns for each remainer option
}
printf("\n");
}
while(--i >= 0)
printf("%c", rev[i]);
Keep all the remainders into an character array and print the array in reverse
Another approach would be a recursive approach (which I wouldn't recommend for very long sequences, but since an integer has a limited number of digits, you can know how deep your recursion would be). It would look something like this (not tested, and somewhat pseudo-codey):
printnum(int n, int b)
{ int r;
if (n < b)
output n;
else
{ r = n % b;
printnum(n/b, b)
output r;
}
}
A good optimizer might even be able to transparently convert that to non-recursive code when you compile.

functions only returning 1?

I'm having an issue where my functions seems to be only returning one. I thought that I was returning the functions correctly but it seems that I am not.
char goAgain()
{
char ch;
do
{
printf("Would you like to go again? ");
ch = getchar();
while(fgetc(stdin) != '\n');
}while(ch != 'n' || 'y');
return ch;
}
double findMedian(int array[], int length)
{
int mid;
double median, medianLeft, medianRight;
if(length % 2 == 0)
{
mid = length / 2;
// medianLeft = array[mid];
// medianRight = array[mid + 1];
}
else
{
mid = length / 2;
median = array[mid];
}
return median;
}
this is how I am calling the median
double mean = findMedian(array, length);
why is it only giving me a one in my return. also when i try to repeat the goAgain I don't get the correct ch to be returned either.
option = goAgain();
things are a lot different in the c world compared to the java world.
do
{
int num = menu();
if(num == 1)
fillArray(array, size);
else if(num == 2)
{
int newSize = readNum();
fillArray(array, newSize);
}
else if(num == 3)
{
int length = size;
sortArray(array);
double mean = findMean(array, length);
double median = findMedian(array, length);
printResults(mean, median);
}
else
{
printf("Please enter a valid number\n");
num = menu();
}
option = goAgain();
}while(option == 'y');
This condition:
(ch != 'n' || 'y')
Is probably not doing what you want. It is interpreted by the compiler like this:
((ch != 'n') || 'y')
Which means "if ch is not the character n OR if the character y". If your machine uses ASCII, then y has the value 121. What happens if you do:
((whatever) || 121)
For the boolean OR operator (||) the value 0 represents false and every other value represents true. And what do you get when at least least of the operands of a boolean OR operation are true? You get true.
So, your condition is, essentially, the same as simply writing
(1)
It looks like you want:
(ch != 'n' && ch != 'y');
When this:
if(length % 2 == 0)
... evaluates true, you don't calculate a value for median, yet still return it.
(And then add in whatever becomes from Carl's answer, which is dealing with the "and also" part of your question!)

Errors in Tic-Tac-Toe Game

I've been trying to code a tic-tac-toe game in C except I've gotten some errors I don't understand. I know this still needs some work but right now I just want to run the program before I add to it. Can someone help me? Here's my code:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int board[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
};
int main (void)
{
int const user1 = 1;
int const user2 = 2;
char move[10];
while (! all_locations_filled()) {
printf("User-1, please enter your move:");
scanf("%s", move[10]);
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
else if(won_the_game(user1)
printf("Congratulations User-1, You Won the Game!");
break;
else
printf("Invalid Move");
printf("User-2, please enter your move:");
scanf("%s", move[10]);
if(valid_location(move[10]))
mark_location(user2, move[10]);
display_board();
else if(won_the_game(user2)
printf("Congratulations User-2, You Won the Game!");
break;
else
printf("Invalid Move");
return 0;
}
bool valid_location(char str[10]) {
int strcmp(x, y);
if (strcmp(str[10], "upperLeft") == 0 || strcmp(str[10], "up") == 0 || strcmp(str[10], "upperRight") == 0 || strcmp(str[10], "left") == 0 || strcmp(str[10], "center") == 0 || strcmp(str[10], "right") == 0 || strcmp(str[10], "lowerLeft") == 0 || strcmp(str[10], "down") == 0 || strcmp(str[10], "lowerRight") == 0)
return true;
}
void mark_location(int userU, char str[10]) {
int strcmp(x, y);
if (strcmp(str[10], "upperLeft") == 0)
board[0][0] = userU;
else if (strcmp(str[10], "up") == 0)
board[0][1] = userU;
else if (strcmp(str[10], "upperRight") == 0)
board[0][2] = userU;
else if (strcmp(str[10], "left") == 0)
board[1][0] = userU;
else if (strcmp(str[10], "center") == 0)
board[1][1] = userU;
else if (strcmp(str[10], "right") == 0)
board[1][2] = userU;
else if (strcmp(str[10], "lowerLeft") == 0)
board[2][0] = userU;
else if (strcmp(str[10], "down") == 0)
board[2][1] = userU;
else if (strcmp(str[10], "lowerRight") == 0)
board [2][2] = userU;
}
char display_board(int array[][]) {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if (array[i][j] == 0)
print("-");
else if (array[i][j] == 1)
print("x");
else if (array[i][j] == 2)
print("o");
}
void all_locations_filled() {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if board[i][j] == 0
return false;
return true;
}
bool won_the_game(userU) {
int i, j;
if (board[0][j] == userU)
return true;
else if (board[1][j] == userU)
return true;
else if (board[2][j] == userU)
return true;
else if (board[i][0] == userU)
return true;
else if (board[i][1] == userU)
return true;
else if (board[i][2] == userU)
return true;
else
return false;
}
Here are the errors the compiler gives me:
tictactoe.c: In function ‘main’:
tictactoe.c:19: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
tictactoe.c:24: error: expected expression before ‘else’
tictactoe.c:115: error: expected declaration or statement at end of input
tictactoe.c:115: error: expected declaration or statement at end of input
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
you have to use "{" and "}" because you have 2 lines.
Use move instead of move[10] in your scanf statement, and when you're passing it to functions. move refers to the array, move[10] just means the 10th position in that array.
Put braces {} around the code in your if / else blocks if they're more than a single line of code (or preferably always, but that's a style issue.)
I found some errors...
scanf("%s", move[10]);
What do you want to do here? If you want to read a string, use
scanf("%s", move );
If you want to read only one character in the 10th position of the array, use
scanf("%c", &move[9] );
Note that your array was declared as move[10], so it's positions go from move[0] to move[9]. Position move[10] is not valid.
Here:
if(valid_location(move[10]))
mark_location(user1, move[10]);
display_board(board[3][3]);
else if(won_the_game(user1)
printf("Congratulations User-1, You Won the Game!");
break;
else
printf("Invalid Move");
You probably meant:
if(valid_location(move[10]))
{
mark_location(user1, move[10]);
display_board(board[3][3]);
}
else if(won_the_game(user1)
{
printf("Congratulations User-1, You Won the Game!");
break;
}
else
printf("Invalid Move");
And here:
void all_locations_filled() {
int i, j;
for (i=0; i<3; ++i)
for (j=0; j<3; ++j)
if board[i][j] == 0
return false;
return true;
}
You forgot the () in the "if". It should be:
if (board[i][j] == 0)
Also, your functions must be declared before you call them. So, declare de functions before main.
You don't have to implement it there, just declare. For example:
void all_locations_filled();
int main (void)
{
...
}
In the last function:
bool won_the_game(userU)
you have to define the type of "userU".
You also forgot to close the brace "}" in the end of the main's while.
You are trying to scan an integer but the scanf argument expects an string (char array). Try %d instead of %s. Thats the Formatstring for Decimal numbers.
If you want to put more then one instruction after an if, you should close it in {}.
Otherwise, the compiler think that only the first is in-condition, and the rest should be done anyway.
scanf("%s", move); not scanf("%s", move[10]);
if(valid_location(move)) not if(valid_location(move[10]))
mark_location(user1, move); not mark_location(user1, move[10]);
if (strcmp(str, "upperLeft") == 0) not if (strcmp(str[10], "upperLeft") == 0)
etc. etc.
You don't do arrays in C by putting square brackets after each and every use of an array. You use the square bracket in basically two situations, you are declaring the array in which case the brackets contain the size of the array, you are accessing an element of the array in which case the brackets contain the index.
You probably won't want to hear this but there's plenty else wrong with your code. You probably need to read a book, and start a bit simpler.
After you've dealt with your compiler errors you might want to look at the function won_the_game which is reading uninitialised variables i and j and will probably give you "access violation" errors as i and j are likely to be out of bounds.
In addition your logic is wrong since obviously you don't win by just occupying one position.

Resources