Home > Blockchain >  Function prints infinitely when in loop, although it's not called repeatedly
Function prints infinitely when in loop, although it's not called repeatedly

Time:01-16

I'm currently trying to solve a problem on Hackerrank where I have to print a pattern. Everything works as it's intended right now, except for the call of my loop function repeat_number inside the loop (!). It prints numbers infinitely, although it should only print it a fixed number of times.

This does not happen, when I call the function before the loop starts. When I print an integer variable it also prints only once. The error only occurs when I call repeat_number inside the loop.

Why is that?

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

void repeat_number(int number_to_repeat, int times_to_repeat) {
    for (int e; e < times_to_repeat; e  ) {
        printf("%d ", number_to_repeat);
    }
}

int main() 
{
    int n;
    scanf("%d", &n);
    // Complete the code to print the pattern.
    
    // get number of rows
    int rows = n * 2 - 1;
    int starting_number = n;
    
    // print row after row
    for (int r; r < rows; r  ) {
        // count down
        for (int i = rows; i > 0; i--) {
            if (starting_number >= 1) {
                printf("%d ", starting_number);
                if (starting_number > 1) {
                    starting_number--;                
                }
                else {
                    break;
                }
            }
        }
        
        // repeat number
        repeat_number(5,1);
        
        // test 
        //int test = 2;
        //printf("%d", test);

        // count up
        for (int j = 1; j < rows; j  ) {
            if (starting_number >= 1) {
                if (starting_number < n) {
                    starting_number  ;                
                }
                else {
                    break;
                }
                printf("%d ", starting_number);
            }
        }
        printf("\n");
    }

    return 0;
}

CodePudding user response:

This line looks very dangerous:

for (int e; e < times_to_repeat; e  )

I would replace it by:

for (int e = 0; e < times_to_repeat; e  )

Because: imagine that e get initialised as some very small number, then you can have an enormous loop: always initialise your variables!

  •  Tags:  
  • Related