2
void checker(int width,int height){
    int horizontal;
    int repeat;
    int i;
    int j;
    for(j=1; j<=height; j++){
        while(horizontal<=width){
            repeat = width/10;
            if(horizontal%2){
                for(i = 1; i <=repeat; i++)
                    printf("1");
            }
            else{
                for(i = 1; i <=repeat; i++)
                    printf("0");
            }
            horizontal++;
        }
        printf("\n");
    }
}

int main(){
    checker(20,10);

    return 0;
}

So I'm creating a pattern through C. As you can tell from my code, I'm barely getting the hang of C. As I compile and test this the pattern doesn't print out in 0's and 1's, rather it only prints the \n.

I was wondering why, I might be having a brain fart.

Thank you for the time, it's very appreciated from new comers like me!

3
  • You should post what you expected to see. Its hard for people to guess what you wanted from just non-working code! Commented Jan 29, 2016 at 21:03
  • 1
    Compile your code with all warnings & debug info (so gcc -Wall -Wextra -g if using GCC...). Learn to use the debugger (gdb) Commented Jan 29, 2016 at 21:08
  • uninitialized variables could cause your issues. Commented Jan 29, 2016 at 21:59

3 Answers 3

3

Horizontal is not properly initialized. Right now you are using garbage value left in memory. Give horizontal a proper value before trying to use it.

Sign up to request clarification or add additional context in comments.

Comments

2

horizontal has not been initialized. unlike some languages, C will not default a non static local variable to 0. It will be just whatever value happens to be in memory.

1 Comment

C will not default a value to 0 Are you sure about that ? How about for example global and static variables which are stored in Data Segment?
1

Change/add line(s):

int horizontal;//not guaranteed to be zero

to

int horizontal = 0;//guaranteed to be zero

Otherwise, this statement may never enter the brackets

while(horizontal<=width){ ... 

Also (not required, but maybe nice to have) add this line just after int j;...

...
int j;

if((width < 0) || (height < 0)) return; //prevent negative input values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.