Home > Software design >  Printing out an exact line in a C program
Printing out an exact line in a C program

Time:05-05

Can you tell me, how I can print out

2
2 4 2
2 4 6 4 2
...

in a program... where N means the number of rows, and the pattern repeats so on...

I get the idea of doing:

#include <stdio.h>

int main(){
    int c, n, col, row, val;
    printf("Provide value of N: ");
    scanf("%d", &n);
    for(row = 0, col = 1, val = 2; row < n; row  , col  = 2){
        for (c = 0; c < col; c  , val  = 2){
            printf("%d ", val);
        }
        printf("\n");
    }
    return 0;
}

but it only does half of the work.

The output is forever ascending... and I do not want that..

2
4 6 8
10 12 14 16 18
...

How could I make it print the numbers in descending order too, when it hits the max value in a row?

CodePudding user response:

The main problem in your code is that you don't reset val after the new row starts. Furthermore, it doesn't contain any logic to manage the descending sequence.

This code behaves as you expect:

#include <stdio.h>

int main()
{
    int c, n, col, row, val;
    printf("Provide value of N: ");
    scanf("%d", &n);
    for(row = 1; row <= n; row  )
    {
        for(val=2; val<=2*row; val =2)
        {
            printf("%d ", val);
        }
        for(val=2*row-2; val>0; val-=2)
        {
            printf("%d ", val);
        }
        printf("\n");
    }
    return 0;
}

Some comments:

  • Start with row 1: it will be useful as the maximum value of each row has to be 2*row
  • Within the first loop, I add two for cycles : the first ascending and the second descending
  • The inner ascending loop has to start from 2 until the value 2*row is reached
  • The inner ascending loop has to start from 2*row-2 (not 2*row, as we already printed that value) until the value 2 is reached (so, we check it to be greater than 0)

CodePudding user response:

You are not subtracting the value again, only ever increasing, and you do not reset your value after each iteration. See a running example based on your code here: https://ideone.com/j6xHZE

#include <stdio.h>

int main() {
    int n, col, row, val;
    printf("Provide value of N: ");
    scanf("%d", &n);
    // Iterate through the desired rows
    for (row = 0; row < n; row  ) {
        val = 0; // Reset val for each row
        // Iterate until we have reached as many columns as the row
        // number we are at
        for (col = 0; col <= row; col  ) {
            val  = 2;
            printf("%d ", val);
        }
        // After this continue one less iteration where we decrease
        // the value
        for (col = 0; col < row; col  ) {
            val -= 2;
            printf("%d ", val);
        }
        printf("\n");
    }
    return 0;
}

Ouptuts:

Provide value of N: 5
2 
2 4 2 
2 4 6 4 2 
2 4 6 8 6 4 2 
2 4 6 8 10 8 6 4 2 
  •  Tags:  
  • c
  • Related