FruitPunchSamurai FruitPunchSamurai - 1 month ago 8
C Question

Passing multiple types of values to functions

I'm trying to do a code with these conditions:

If R is true, a character will replace the * for an 'O', if row = 0 , if step = 2 this should be the output 2nd situation if R is true, if row = 3, if step "column" is 4.

* O * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * O


The user will enter the values for row and step. The variables for
R
,
Row
and
step
have to be manipulated using functions then printed in
int main
.

#include <stdio.h>
#include <stdlib.h>

void Direction(char z) {
printf("Walking to the right\n");
z = getchar();
}

void RowAndSteps(char z, int c, int f) {
if (z == 'R') {
printf("Row\n");
scanf("%d", &c);

printf("Steps");
scanf("%d", &f);
}
}

void print(char a[4][4]) {
int i, k;
for (i = 0; i < 4; i++) {
for (k = 0; k < 4; k++) {
printf("%c ", a[i][k]);
}
printf("\n");
}
}

int main() {
char a[4][4] = {
{ '*', '*', '*', '*' },
{ '*', '*', '*', '*' },
{ '*', '*', '*', '*' },
{ '*', '*', '*', '*' } };

Direction(z);
RowAndSteps(z, c, f);
a[c][f] = 'O';

print(a);
return 0;
}

Answer

You really need to get a good book so that you can learn about the C programming language. In particular, the problems in your code above seem rooted in misunderstandings about variable scope and how variables are passed to and from functions.

I have fixed up your code, doing the minimum amount necessary to make it run. I changed the formatting a bit to make it more readable, and broke your RowAndSteps() function into two functions (because C only allows a function to return one value). I added declarations where necessary. The new functions are only passed information that they need, and they each return a value. Your print() function was fine-- you correctly gave it an array, and it doesn't need to return a value.

There are plenty of problems left for you to solve. For example, how should your program handle malformed input? What if the user tries to walk off of the 4X4 grid?

Here is the modified code:

#include <stdio.h>
#include <stdlib.h>

char direction(void)
{
  printf("Walking to the right\n");

  return getchar();
}

int getRow(char z)
{
    int c;

    if (z == 'R') {
        printf("Row\n");
        scanf("%d", &c);
    }

    return c;
}

int getSteps(char z)
{
    int f;

    if (z == 'R') {
        printf("Steps: ");
        scanf("%d", &f);
    }

    return f;
}

void print(char a[4][4])
{
    int i, k;

    for (i = 0; i < 4; i++) {
        for (k = 0; k < 4; k++) {
            printf("%c ", a[i][k]);
        }
        printf("\n");
    }
}

int main(void)
{
    char z;
    int c, f;  
    char a[4][4] = {
        { '*', '*', '*', '*' },
        { '*', '*', '*', '*' },
        { '*', '*', '*', '*' },
        { '*', '*', '*', '*' }
    };

    z = direction();
    c = getRow(z);
    f = getSteps(z);

    a[c][f] = 'O';

    print(a);

    return 0;
}