Home > Software engineering >  Printing out each time 2 more elements of an array
Printing out each time 2 more elements of an array

Time:05-03

How can I print out each line two more elements of an array...?
I can't get it done.
I have this short code, but this part is missing...

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

char *toChar(int numbers[]);

int main(){
//  FILE *fp;
    int num;
    printf("Number of rows: ");
    scanf("%d", &num);
    int val[num], value=num;
    for(int i=0; i<num; i  ){
        val[i]=value;
        value =value;
        printf("%d ", val[i]);
            ...
            printf("\n");
        }
    }
    return 0;
}

I would like to achieve this... for input = 4.

4   8
12  16  20  24
28  32  36  40  44  48
52  56  60  64  68  72  76  80

And for input 3, expected output is:

3   6
9   12  15  18
21  24  27  30  33  36

Thanks in advance...

CodePudding user response:

I would make a list of all you need:

  • You need num rows
  • You need the number of columns to increase by 2 every row
  • You need the printed value to increase by num for each output

With that list, make two loops.

  • One that iterates over the rows
  • One that iterates over the columns:
#include <stdio.h>

int main() {
    printf("Number of rows: ");

    int num;
    if (scanf("%d", &num) != 1) return 1;

    // row starts at 0 and ends at num-1
    // columns start with 2 and increases by 2 for every row
    for (int row = 0, columns = 2, value = num; row < num;   row, columns  = 2) {
        // and value increases by `num` every time it's been printed:
        for (int c = 0; c < columns;   c, value  = num) {
            printf("%d ", value);
        }
        putchar('\n');
    }
}

Demo

CodePudding user response:

Decided to take a stab at this using java. I feel like recursion here was a bit easier than trying to wrap my head around two for loops.

class Main {
  public static void main(String[] args) {
    printTwoMore(0, 1, 1, 4);
  }

  public static void printTwoMore(int prevTimesToPrint, int multiple, int currentRow, int maxRow) {

    if (currentRow > maxRow) {
      return;
    }

    int timesToPrint = 2   prevTimesToPrint;

    for (int i = 0; i < timesToPrint; i  ) {
      System.out.print(4 * multiple   " ");
      multiple  ;
    }

    System.out.println("");

    currentRow  ;

    printTwoMore(timesToPrint, multiple, currentRow, maxRow);
  }

}
  •  Tags:  
  • c
  • Related