Sunday, December 10, 2023
HomeC ProgrammingProducing a Desk from Stream Output

# Producing a Desk from Stream Output

This month’s Train looked for and output the primary 100 cyclops numbers. However as an alternative of spewing them out in a protracted column, my resolution set them in a desk. The values marched throughout the display in neat rows. This trick is relatively straightforward to perform, however in my resolution I needed some flexibility with the column quantity.

I took code from the related a part of my Train resolution and rebuilt it right here to output sequential values:

### 2022_09_10-Lesson.c

```
#embrace <stdio.h>

int essential()
{
const int columns = 9;
const int values = 100;
int x,y,depend;

x = 0;
depend = values;
whereas( depend )
{
for( y=0; y<columns; y++ )
{
printf("%3d",(x*columns)+y );
count--;
if( !depend )
break;
if( y<columns-1)
putchar('t');
}
x++;
putchar('n');
}

return(0);
}```

The variety of `columns` is ready as a relentless, as is the `values` depend. I needed the desk output to deal with a variable variety of columns, but additionally to take care of a state of affairs when the final row doesn’t have a worth for every column.

The nested for loop handles the values throughout a row. The important thing to outputting the values sequentially is discovered within the printf() assertion: `(x*columns)+y)` This expression bases every row’s values on variable `x`, which is the row depend, occasions the whole variety of columns. Including the `y` worth completes the duty, as every worth is output sequentially, left-to-right, top-down, as proven in Determine 1. Determine 1. The output displaying 100 values in 9 columns.

The expression `x*columns` increments the beginning (first column) worth by the worth of columns: 0, 9, 18, and so forth. The remainder of the row then falls into place based mostly on the worth of variable `y`.

This code is constructed in order that the column quantity might be adjusted with out requiring the loops to be rebuilt. If I set the worth of fixed `columns` to 5, the output adjustments as proven in Determine 2. Determine 2. Desk output when the `columns` fixed is ready to 5.

When the rows and columns are even, as proven in Determine 2, the final row is full. However in Determine 1, you see just one merchandise on the ultimate row. The code that handles that is an if choice after the printf() assertion outputs the worth:

`if( !depend )    break;`

Variable `depend` is decremented after output. If its worth is zero, values are exhausted and the row can finish: The for loop stops and a newline is output. As a result of `depend` is zero, the outer whereas loop stops as properly.

Desk output raises the issue degree over simply spewing out every quantity on a line by itself. This methodology, rows throughout, is less complicated than coding a desk the place the values are set in columns marching left-to-right. I cowl such a desk output in subsequent week’s Lesson.

RELATED ARTICLES