简体   繁体   中英

How to printf to next line when function is executed for the 2nd time in C?

Solving a problem. But my output is not matching with the expected output.

Input:

2
16
10

Expected Output:

16 11 6 1 -4 1 6 11 16
10 5 0 5 10

Actual Result:

16 11 6 1 -4 1 6 11 16 10 5 0 5 10

I have almost tried all the escape sequences, ie "\\n" "\\t" , etc.

#include <stdio.h>
#include <stdbool.h>

void printPattern(int n, int m, bool flag) {
    printf("%d ", m);

    if (flag == false && n == m)
        return;

    if (flag) {
        if (m - 5 > 0)
            printPattern(n, m - 5, true);
        else
            printPattern(n, m - 5, false);
    } else 
        printPattern(n, m + 5, false);        

    //return 0;
}

int main() {
    //int n = 16;

    int t, n;
    scanf("%d", &t);

    while (t-- > 0) {
        scanf("%d", &n);
        printPattern(n, n, true);
    }
    return 0;
}

Input:

2
16
10

Expected Output:

16 11 6 1 -4 1 6 11 16
10 5 0 5 10

Actual Result:

16 11 6 1 -4 1 6 11 16 10 5 0 5 10

You just need to print a linefeed after you invoke printPattern in the loop.

while(t-->0){
    scanf("%d", &n);
    printPattern(n,n,true);
    printf("\n");
}

I wouldn't put the linefeed print in the recursive printPattern function itself. You want to print one line for each number you're reading from input and this solution best reflects your intent.

You could also do putchar('\\n') instead of printf .

Add printf("\\n") after the second time you call printPattern() :

void printPattern(int n,int m, bool flag)
{
    printf("%d ", m);
    if(flag == false && n==m)
        return;
    if(flag)
        if(m-5>0)
            printPattern(n,m-5, true);
        else
        {
            printPattern(n,m-5,false);
            printf("\r\n"); /* Sometimes the carriage return is required in Windows
                               operating systems to simulate line break... */
        }
    else 
      printPattern(n,m+5,false);        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM