Use loop to print values as requested - loops

Hi question how do I print out above in console from processing.
int result;
for (int i=100 ; i < = 10; i + = 10) {
result = 100;
for (int k=2; k <= 10; k++) {
result-=10 ;
} print(result);
println();
}
My thought is it looks like a 10*10 table thus both i and k is < =
10.
And other thought is when i is odd i starts from 100 and -=10 (i > = 10)
when i is even(line 2,4,6...) i start from 10 and +=10 ( i<=100) Then I got the printed table.
But I am stuck how to achieve
this in code if my logic is correct as mentioned above.

You can do it with 2 nested loops:
for (int i=0; i<10; ++i) {
for (int j=0; j<10; ++j) {
print(str(i%2 == 0 ? (10-j)*10 : (j+1)*10) + " ");
}
println();
}
Or one single loop:
for (int i=0; i<100; ++i) {
int j = i%10;
print(str((i/10)%2 == 0 ? (10-j)*10 : (j+1)*10) + " ");
if (i % 10 == 9) {
println();
}
}
Output:
100 90 80 70 60 50 40 30 20 10
10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
10 20 30 40 50 60 70 80 90 100

This is a simple example showing that logic in javascript.
It doesn't use the double loop nor smart increments inside the for condition statement, but it just increments an index from 1 to 10 using a condition with the ternary operator (over a flag that gets flipped at each iteration) to output one fashion or the other.
It's not the most elegant solution and it uses multiplications. I'm sure you'll find smartest ways to achieve the same.
let alt = true;
let counter = 0;
//infinite loop
while(true){
counter++;
let row = "";
for(let i=1; i<=10; i++){
row += (alt) ? (10*i) + ' ' : 110-(10*i) + ' ';
}
//output current row
console.log(row);
//switch alternate
alt = !alt;
//exit at iteration 10
if(counter == 10) break;
}

Here's yet another variation:
void setup() {
print(reversingNumberLoop(10, 100, 10, 9));
}
String reversingNumberLoop(int from, int to, int increment, int rows){
String result = "";
String backToFront = "";
String frontToBack = "";
// loop once writing in both directions
for(int i = from; i <= to; i+= increment){
frontToBack += i + " ";
backToFront += ((to - i) + from) + " ";
}
// add line endings
frontToBack += "\n";
backToFront += "\n";
// repeat for the number of rows
for(int i = 0 ; i < rows; i++){
result += i % 2 == 1 ? frontToBack : backToFront;
}
return result;
}
It's not doing anything too clever: still using % to alternate and just pre-allocates the repeating lines first. This would have two loops in succession, not nested.

Related

Determining if an array of numbers contains a specific element within 2D character array

Overview
I am currently writing a C program that simulates a bingo checker. In this program, a user enters a 2D Array, a string of numbers, followed another 2D array. All done through standard input.
The first 2D array is the bingo pattern. The 1D array is the numbers called during the game. The second 2D array is the player's actual pattern on their card. The purpose of the program is to determine if their bingo is valid or invalid. A sample input is as follows:
1 0 0 0 0
1 0 0 0 0
1 0 0 0 0
1 0 0 0 0
1 1 1 1 1
12 20 15 40 45 32 71 07 56 51 36 55 19 10 43 23 70 11 27 60 67 03 72 33 56 09 02
12 29 39 57 61
15 30 45 60 75
07 23 00 46 68
02 18 37 51 70
10 27 32 55 71
Problem
Since I have to compare the arrays with the strings of numbers, I thought it would be easier to create a third 2D array, named playerPattern, which is also filled with ones and zeros. In the final block of code in the snippet below, the program checks if the value in the current position of the player's actual board, playerBoard, is within the numbersCalled array. If so, it places a 1 in that spot. Then, it will compare the first 2D array, bingoPattern with playerPattern.
However, in the final for-loop, the if condition is causing the program to halt and throw a signal 11 disruption.
if (strcmp(currentArrayElem, currentNumCalled) == 0 { strcpy(&playerPattern[row][col], "1");
}
I can not figure out why the memory allocation is an issue here, as the pointers seem to be set-up correctly.
// necessary import statements
#include <stdio.h>
#include <string.h>
int main() {
char* bingoPattern[5][5]; // array to store initial bingo pattern (1's and 0's)
char* playerBoard[5][5]; // array to store player's actual bingo board
char* playerPattern[5][5]; // array to store player's actual bingo pattern
char inputNumString[225]; // undelimited string of numbers for initial standard input
// read-in bingo pattern
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
fscanf(stdin, "%d", &bingoPattern[i][j]); } }
// read-in numbers called
fgets(inputNumString, 225, stdin); // skip empty line
fgets(inputNumString, 225, stdin); // collect string input
fgets(inputNumString, 225, stdin); // skip empty line
char *numbersCalled[75]; // final array of delimited elements
char singleNumber; // single string of delimited numbers
inputNumString[strlen(inputNumString + 1)] = 32;
singleNumber = strtok(inputNumString, " ");
int numCalledCount = 0; // stores amount of numbers called
while (singleNumber != NULL) {
numbersCalled[numCalledCount] = singleNumber;
numCalledCount = numCalledCount + 1;
singleNumber = strtok(NULL, " ");
}
// read-in player's actual board
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
fscanf(stdin, "%d", &playerBoard[i][j]);
}
}
// populate player pattern with zero's
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
playerPattern[i][j] = 0;
}
}
// create player pattern
char* currentNumCalled;
char* currentArrayElem;
for (int currentNumber = 0; currentNumber < numCalledCount; currentNumber++) {
currentNumCalled = numbersCalled[currentNumber];
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
currentArrayElem = &playerBoard[row][col];
if (strcmp(currentArrayElem, currentNumCalled) == 0) {
strcpy(&playerPattern[row][col], "1");
}
}
}
}
return 0;
}

C Multiples of a number from 1 to 100 going over 100

I'm creating a program that calculates the multiples of seven from 1 to 100. However my code prints one multiple above 100, 105. I'm not sure how to fix this. I've tried doing num <= 100, num < 100, num < 99, num = 0, but nothing works. Thank you!
Code:
int main()
{
//variables
int i = 1, num;
printf("Multiples of Seven from 1 to 100: \n");
while(num < 100) {
num = i * 7;
printf(" %d ", num);
i++;
} //while end
} //main end
Make while loop condtion as,
while(i * 7 <= 100)
or change the lines from this:
num = i * 7;
printf(" %d ", num);
to this:
printf(" %d ", num);
num = i * 7;
if you choose to go this way you should initialize num..
this is the output
Multiples of Seven from 1 to 100:
0 7 14 21 28 35 42 49 56 63 70 77 84 91 98

C language wrong output...pascal triangle using 2d arrays

So this is my code for printing pascal triangle using 2d arrays but its not giving me the desired output and I cannot determine what's wrong with the logic/code.
#include <stdio.h>
int main()
{
int num, rows, col, k;
printf("Enter the number of rows of pascal triangle you want:");
scanf("%d", &num);
long a[100][100];
for (rows = 0; rows < num; rows++)
{
for (col = 0; col < (num - rows - 1); col++)
printf(" ");
for (k = 0; k <= rows; k++)
{
if (k == 0 || k == rows)
{
a[rows][k] = 1;
printf("%ld", a[rows][k]);
}
else
a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
printf("%ld", a[rows][k]);
}
printf("\n");
}
return 0;
}
You don't have curly braces around the statements after the else, so it looks like you'll double-printf() when the condition of the if-statement is true.
I copied the source into codechef.com/ide and changed the io for num to be just assigned to 6 which produced the following output:
Enter the number of rows of pascal triangle you want:
11
1111
11211
113311
1146411
1151010511
It looks like your close, but you want 1, 11, 121, 1331 etc right?
Wraping the else case produced the following output:
if (k == 0 || k == rows)
{
a[rows][k] = 1;
printf("(%ld)", a[rows][k]);
}
else{// START OF BLOCK HERE
a[rows][k] = (a[rows - 1][k - 1]) + (a[rows - 1][k]);
printf("(%ld)", a[rows][k]);
}//END OF BLOCK HERE, NOTE THAT IT INCLUDES THE PRINT IN THE ELSE CASE NOW
OUTPUT:
Enter the number of rows of pascal triangle you want:
(1)
(1)(1)
(1)(2)(1)
(1)(3)(3)(1)
(1)(4)(6)(4)(1)
(1)(5)(10)(10)(5)(1)
But i added () to make it clearer to me. I also added a "/n" to the end of the first printf that asks for the value of num, so that the first line is on a new line.
printf("Enter the number of rows of pascal triangle you want:\n");
You can do that without using any arrays:
#include <stdlib.h>
#include <stdio.h>
int num_digits(int number)
{
int digits = 0;
while (number) {
number /= 10;
++digits;
}
return digits;
}
unsigned max_pascal_value(int row)
{
int result = 1;
for (int num = row, denom = 1; num > denom; --num, ++denom)
result = (int)(result * (double)num / denom );
return result;
}
int main()
{
printf("Enter the number of rows of pascals triangle you want: ");
int rows;
if (scanf("%d", &rows) != 1) {
fputs("Input error. Expected an integer :(\n\n", stderr);
return EXIT_FAILURE;
}
int max_digits = num_digits(max_pascal_value(rows));
for (int i = 0; i <= rows; ++i) {
for (int k = 0; k < (rows - i) * max_digits / 2; ++k)
putchar(' ');
int previous = 1;
printf("%*i ", max_digits, previous);
for (int num = i, denom = 1; num; --num, ++denom) {
previous = (int)(previous * (double)num / denom );
printf("%*i ", max_digits, previous);
}
putchar('\n');
}
}
Output:
Enter the number of rows of pascals triangle you want: 15
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1

Trying to get a user input to make a 2-D array multiplication table

int main (void)
{
int range, i, j;
printf("Input size of multiplication table: ");
scanf("%i", &range);
int output[range][range];
for (i = 0; i<=range; ++i)
{
for (j=0; j<=range; ++j)
{
output[i][j] = i * j;
if(j!=range && output[i][j] != 0)
{
printf("%3i ", output[i][j]);
}
else if (j==range)
{
printf("%3i", output[i][j]);
}
else if (output[i][j] == 0)
{
printf("%3i "), i+2;
}
else
{
printf("%3i", j + i - range);
}
}
printf("\n");
}
return 0;
}
I am having it output:
0 1 2 3 4 0
5 1 2 3 4 5
10 2 4 6 8 10
15 3 6 9 12 15
20 4 8 12 16 20
25 5 10 15 20 25
and I need the 0 on the end to be a five and the first column to be 0,1,2,3,4,5 instead of 0,5,10,15,20,25.
If anyone could help I would appreciate it.
You have two primary problems, (1) you fail to validate your user input, and (2) your loop bounds are incorrect, e.g.
Any time you take user input, you must validate that you actually received what you expected and that any conversion required, was completed successfully. Failure to validate will lead to Undefined Behavior it invalid (or no) input is provide. (e.g. What if the user enters foo instead of 10?) When using scanf, you must validate the return which provides the count of the number of conversions that successfully took place, e.g.
printf ("Input size of multiplication table: ");
if (scanf("%i", &range) != 1) { /* VALIDATE ALL USER INPUT */
fprintf (stderr, "error: invalid input.\n");
return 1;
}
That is bare minimum. You can also check if the return is EOF to indicate the user canceled input with a [Ctrl+D] (or [Ctrl+Z] on windoze -- must be explicitly enabled on Win10).
Next, your loop bound are for (i = 0; i < range; i++) not i <= range, that invokes Undefined Behavior by attempting to access memory outside your array bounds. Simply fix the loop condition, e.g.
for (i = 0; i< range; i++) { /* fill multiplication table */
for (j = 0; j< range; j++) {
output[i][j] = (i + 1) * (j + 1); /* i+1 * j+1 */
}
}
Putting it altogether, you could do something similar to:
#include <stdio.h>
int main (void) {
int range, i, j;
printf ("Input size of multiplication table: ");
if (scanf("%i", &range) != 1) { /* VALIDATE ALL USER INPUT */
fprintf (stderr, "error: invalid input.\n");
return 1;
}
int output[range][range]; /* variable length array */
for (i = 0; i< range; i++) { /* fill multiplication table */
for (j = 0; j< range; j++) {
output[i][j] = (i + 1) * (j + 1); /* i+1 * j+1 */
}
}
for (i = 0; i< range; i++) { /* output table */
for (j = 0; j< range; j++)
printf (" %3d", output[i][j]);
putchar ('\n');
}
return 0;
}
note: the trivial parts of the table is omitted (e.g. 0 * anything), and duplicated rows of 1 * anything are also not shown. If you need to additional rows, you can add them back.
Example Use/Output
$ ./bin/multable
Input size of multiplication table: 10
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Look things over and let me know if you have further questions.
To Show the 1X Rows
You simply update your print routine as follows:
for (i = 0; i< range; i++) { /* output table */
if (!i) {
printf (" ");
for (j = 0; j< range; j++)
printf (" %3d", output[i][j]);
putchar ('\n');
}
printf (" %3d", i + 1);
for (j = 0; j< range; j++)
printf (" %3d", output[i][j]);
putchar ('\n');
}
Example Use/Output
$ ./bin/multable1
Input size of multiplication table: 10
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100
Check the solution below. It's all about properly managing iterators (note the less-equal sign in the ranges and the subtraction of indexes by 1 in the assignment). You can do it very concisely by assigning to output inside the printf and using a ternary-if. (I also used dynamic allocation in order to comply with ISO standards.)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int range, i, j;
printf("Enter the size of the multiplication table:\n");
scanf("%d", &range);
int ** output = (int **) malloc(sizeof(int *) * (long unsigned int) range);
for(i = 0; i <= range; ++i)
{
output[i] = (int *) malloc(sizeof(int) * (long unsigned int) range);
for(j = 0; j <= range; ++j)
printf("%3d ", !i ? j : !j ? i : (output[i - 1][j - 1] = i * j));
printf("\n");
}
return 0;
}

Error in scanf()

first of all, I've got a logical error in my code. Well, this is the code
#include <stdio.h>
int main()
{
long i,j,t;
scanf("%ld",&t);
long n[t],d[t][t];
for(i = 0; i < t;i++){
scanf("%ld",&n[i]);
for(j = 0; j < n[i] ;j++){
scanf("%ld",&d[j][i]);
}
}
for(i = 0; i < t;i++){
for(j = 0; j < n[i] ;j++){
printf("%ld ",d[j][i]);
}
printf("\n");
}
return 0;
}
And I input the data
2
4
25 20 30 90
3
45 50 55
And the result is
25 20 30 90
45 50 55
Well, that's what I expected. However, when the input become like this
3
5
12 67 89 34 56
6
34 56 78 90 12 34
7
12 34 89 23 56 78 89
The result become like this
12 34 89 23 56 78 89
12 67 89 34 56 4206692 7 2293472 1982002386 16 3 2293344 2293408 0 2293552 0 0 4
198585 8918456 1982106837 1982010910 8918456 2293640 0 0 1985286516 2009576437 0
0 2293664 2009323341 2293740 2147348480 0
34 56 78 90 12 34 4199405 1982595752 8 12 2293424 2 2 1982356412 2147348480 2293
608 2147348480 1 -1 297753669 1982010784 1982015505 4199044 0 0 2147348480 21473
48480 0 0 0 7273647 2009576392 0 0 0 1 0 20 52 0 0 438759246 736 -214797894 1420
760826203 2272 852421325 3108 944791496 4028 -1322777276 4988 9 1 1 1204 7168 4
2 152 11832 7 1 40 12316 1682469715 1 140 44 0 0 0 2 0 7209065 5701724 6029427
12 34 89 23 56 78 89
Well, the simple question, why the output become like the above?? When I input above 2, the same result will be happened. Any possible answers and links if you don't mind it?? Thanks
You are writing outside your 2D array in many cases, sometimes you don't get errors, but that's just by chance.
You determine the size of the 2D array by the number of arrays to be inputted, but you also determine the size of the inner arrays at the same time:
scanf("%ld",&t);
long n[t],d[t][t];
So for example, let's take the first example:
2 >> create array n[2], and array d[2][2]
4 >> number of values to d[0]
25 20 30 90 >> d[0][1] = 25 d[0][2] = 20 you access d[0][3] and d[0][4] but you are not allowed to do that.
3 >> number of values to d[1]
45 50 55 >> d[1][0] = 45 d[1][1] = 50 you access d[1][2] but you are not allowed to do that
You build a matrix with size t*t, then fill in rows with more or less elements.
If you fill a row with too few elements, the rest remain uninitialized, and you get strange numbers. It's OK in your case, because you don't print these elements.
If you fill a row with too many elements, the excess overlaps into the next row. It may also exceed the whole matrix and corrupt your stack.
I guess this is what's going on - your n array is overrun, and your code goes crazy.
I believe that you can use malloc.
#include <stdio.h>
#include <stdlib.h>
int main()
{
long i,j,t;
printf("Rows : ");
scanf("%ld",&t);
long *n;
long **d;
n = (long* )malloc(sizeof(long) * t); // add malloc
d = (long** )malloc(sizeof(long *) * t); // add malloc
for(i = 0; i < t;i++){
printf("Column : ");
scanf("%ld",&n[i]);
d[i] = (long* )malloc(sizeof(long) * n[i]); //add malloc
if(d[i] == NULL)
printf("ERROR\n");
for(j = 0; j < n[i] ;j++){
scanf("%ld", &d[i][j]); // change from &d[j][i]
}
}
printf("\n\n");
for(i = 0; i < t;i++){
for(j = 0; j < n[i] ;j++){
printf("%ld ",d[i][j]); // change from d[j][i]
}
printf("\n");
}
return 0;
}
Well, the simple question, why the output become like the above?? When
I input above 2, the same result will be happened. Any possible
answers and links if you don't mind it?? Thanks
because you allocate less memory than used.
scanf("%ld", &d[j][i]); you have to exchange the "i" and "j".

Resources