Search code examples
cparametersprogram-entry-pointatoi

How to print a square based on main parameters


So I have this code. I am stuck on this trial where the parameter to main is ["2"].

    #include <stdlib.h> 
    #include <stdio.h>
    
    void my_square(int x, int y) {
    
        if(x == 5 && y == 3){
            printf("o---o\n");
            printf("|   |\n");
            printf("o---o\n");
        }
        if(x == 5 && y == 1){
            printf("o---o\n");
        }
        if(x == 1 && y == 1){
            printf("o\n");
        }
        if(x == 1 && y == 5){
            printf("o\n");
            printf("|\n");
            printf("|\n");
            printf("|\n");
            printf("o\n");
        }
        if(x == 4 && y == 4){
            printf("o--o\n");
            printf("|  |\n");
            printf("|  |\n");
            printf("o--o\n");
        }
        if(x == 2 && y == 2){
            printf("oo\noo\n");
        } 
        if(x == 2 && y == 0){
            printf("");
        }
        
    }
    
    int main(int argc, char *argv[]){ 
        if(atoi(argv[1]) && atoi(argv[2])){
            my_square(atoi(argv[1]),atoi(argv[2]));
        } 
        if( atoi(argv[1]) && atoi(argv[2]) == '\n'){
            my_square(atoi(argv[1]), 0);
        }
    
        return  0;
    }

Tester With input ["2"], Output should be an empty space. But I don't know how write the code to solve this. Any thoughts on how to do this ? Thank you in advance.


Solution

  • atoi(argv[2]) == '\n' is not the correct way to tell if the second argument was omitted and you need to provide a default value for it. If only one argument is supplied, argv[2] will be NULL, and you can't pass it to atoi(). Also, '\n' is equivalent to 10 -- why would you expect atoi() to return that number for a nonexistent value?

    To tell how many arguments were supplied, check argc.

    int main(int argc, char *argv[]) {
        if (argc == 2) {
            my_square(atoi(argv[1]), 0);
        } else if (argc > 2) {
            my_square(atoi(argv[1]),atoi(argv[2]));
        } else {
            printf("Usage: %s x [y]\n", argv[0]);
        }
        return 0;
    }
    

    In my_square() if you want to print a line containing an empty space, use:

    if (x == 2 && y == 0) {
        printf(" \n");
    }
    

    printf("") doesn't print anything at all.

    You also should use else if in my_square(), since all the conditions are mutually exclusive. There's no point in checking all the remaining combinations once you've found a match.