I am just starting to dive into 2D arrays and I am having some trouble why my output is producing a line of data rather than the dimensional matrix. All help is appreciated! Thank you!!
My code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int x, y, i, j;
int m[10][10];
setvbuf(stdout, NULL, _IONBF, 0);
while (1) {
printf("Number of rows? ");
scanf("%d", &x);
if (x == 0)
break;
printf("Number of columns? ");
scanf("%d", &y);
printf("Enter matrix values row by row: \n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
scanf("%d", &(m[i][j]));
}
}
printf("Matrix read:\n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d", m[i][j]);
}
}
Imputed data:
Number of rows? 2
Number of columns? 2
Enter matrix values row by row:
1 2 3 4
Output:
Matrix read:
1234
To figure out why your current program is printing the line, go through the printing loop, and look at all points where you are printing the values.
You will notice that it will be something like this:
print "1", print "2", print "3", print "4".
So, the program just does that. It prints the numbers without any other "formatting" around.
You can do something like this:
printf("Matrix read:\n");
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
Notice there's a space after the number in the literal "%d ".
And then, notice that a new line is printed after every inner for loop (which corresponds to a row).
Note: You may want to use more descriptive names. Eg: row instead of x
and column instead of y.
Your program is perfectly fine. It is printing the matrix in correct order too. However if you just want to format the output in a matrix format, just print "\t" and "\n" after the inner and outer loop respectively.
for (i = 0; i < x; i++) {
for (j = 0; j < y; j++) {
printf("%d\t", m[i][j]);
}
printf("\n");
}
Related
I want to create a program that can read scores from user and display the scores output in the form of stars. But it seems that my code keep getting an infinity loop. Can anyone tell me what is wrong with my looping.
#include <stdio.h>
int main() {
int i, k, j;
int score[5];
for(i = 1; i < 6; i++) {
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 1; k < 6; k++) {
printf("%d. ", k);
for (j = 1; j <= score[k]; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Array indices are 0 based in C. So for an array with 5 elements the indices are from 0-4 inclusive. You are using indices 1-5 which results in buffer overflow. Below is the corrected program with the for loops fixed up to use the right indices:
#include <stdio.h>
#define NUM_SCORES 5
int main()
{
int i, k, j;
int score[NUM_SCORES];
for(i = 0; i < NUM_SCORES ; i++)
{
printf("\nplease enter the score for %d match : ", i);
scanf("%d", &score[i]);
}
printf("\nstatistics collection points for 5 matches\n\n");
for (k = 0; k < NUM_SCORES ; k++){
printf("%d. ", k);
for(j = 1; j <= score[k]; j++){
printf("*");
}
printf("\n");
}
return 0;
}
You should also add a check to ensure scanf is able to successfully read each input.
When i want to print a matrix which i input,i can use code:
#include <stdio.h>
int main(void)
{
int n, m; //row and column
printf("Enter row and column:\n");
scanf("%d %d", &n, &m);
int x[n][m];
printf("Enter your matrix:\n");
for (int i = 0; i < n; i++) //input my matrix
{
for (int j = 0; j < m; j++)
{
scanf("%d", &x[i][j]);
}
}
printf("print it:\n");
for (int i = 0; i < n; i++) //print it
{
for (int j = 0; j < m; j++)
{
printf("%d ", x[i][j]);
}
putchar('\n');
}
}
enter image description here(a possible case)
In code above, I have to assign values to the rows and columns of the matrix,which named "n" and "m".
int n, m;
scanf("%d %d", &n, &m);
But now I am asking a way to automatic tally .
Can I get this one directly?
enter image description here
You can simulate a two-dimensional array with a one-dimensional array, if that's what you mean:
#include <stdio.h>
#include <stdlib.h>
#define DIGITS 3
int main(void) { // It's good practice to fill function arguments with void if not planning on using them
/* scanf("%d %d", &n, &m); Using scanf with uninitialised variables will result in
* undefined behaviour if it is unable to convert the input. Using fgets
* is easier to debug, safer, and cleaner.
* I highly recommend this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
*/
char buf[DIGITS+1];
printf("%s", "Enter array rows:");
fgets(buf, DIGITS+1, stdin);
const int n = atoi(buf);
printf("%s", "Enter array columns:");
fgets(buf, DIGITS+1, stdin);
const int m = atoi(buf);
int x[n*m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("Enter array value at %d, %d: ", i, j);
fgets(buf, DIGITS+1, stdin);
x[i+j] = atoi(buf);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", x[i+j]);
}
printf("\n");
}
}
I'm not really sure as to why you would do this when C supports your two-dimensional array answer equally.
But now I am asking a way to automatic tally. Can I get this one directly?
Yes.
Form a linked-list of lines. Initially the list is empty.
Read the first line of input, the "1 2 3" into a string. Use fgets().
Parse the line to detect the number of values in it.
Append the line to the linked list of lines.
Continue doing so until 1) end-of-file, 2) a blank line or 3) number of integer is not the same as the first (error condition).
Now code has the m (number of values per line) and n, the number of lines.
Form int x[n][m];
Parse the lines for values and save in x.
i have some problem making this program
I have created two arrays where I go to insert the first and the last line, then I check if every element is > 0 but it doesn't seem to work..
That's my code:
int main()
{
int i, j, n, m;
int matrix[10][20];
int first_row[m];
int last_row[m];
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(matrix[i=0][j]) // First row
first_row[i] = matrix[i=0][j];
if(matrix[i=n-1][j]) // second row
last_row[i] = matrix[i=n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=j+1;j<n;j++)
{
if(last_row[i] < 0)
printf("Negative element");
}
}
}
I assume in the if conditions matrix[i=0][j] and matrix[i=n-1][j] was to check if the current row being input is the first or last row respectively. If that was the case then you just need to simply check if i is 0 (i == 0) or n - 1 (i == n-1) instead of using matrix[i=0][j] and matrix[i=n-1][j].
Also the line first_row[i] = matrix[i=0][j]; and last_row[i] = matrix[i=n-1][j]; will update i which is what you should avoid in a for loop where i is index. If you intended to assign values to first_row and last_row, you should change them to first_row[j] = matrix[0][j]; and last_row[j] = matrix[n-1][j]; to a get the desire result (note that j should be used for indexing first_row and last_row instead of i because j represents matrix column).
If you want to check every element in the matrix for negative values, then the for loop for (j=j+1;j<n;j++) should be changed to for (j=0;j<m;j++) and matrix[i][j] should be used instead of last_row[i].
Edit: Also as #chux suggested, you should consider initializing matrix, first_row and last_row arrays after you input n and m in order to avoid segmentation fault for any n and m values that are larger than 10 and 20 respectively.
#include <stdio.h>
int main()
{
int i, j, n, m;
printf("Enter number of rows : ");
scanf("%d", &n);
printf("Enter number of columns : ");
scanf("%d", &m);
int matrix[n][m];
int first_row[m];
int last_row[m];
/* Input data in matrix */
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("Enter data in [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
if(i == 0) // First row
first_row[j] = matrix[0][j];
if(i == n-1) // second row
last_row[j] = matrix[n-1][j];
}
}
for(i=0;i<n;i++)
{
for (j=0;j<m;j++)
{
if(matrix[i][j] < 0)
printf("Negative element %d\n", matrix[i][j]);
}
}
}
My program should ask user how many numbers he wanna input in the array , and than input one by one. Any number that's higher than 99 should be replaced by '0'.
That part works fine. But in the end created array should be placed in the table which needs to be in format (5 columns / depending rows).
This is what I wrote:
#include <stdio.h>
#define MAX 80
int main()
{
int n = 0;
int i,j;
int field[MAX]={0};
printf("how many numbers do u want to input? ");
scanf("%d",&n);
for ( i = 0; i < n; i++)
{
printf("Input number %d: ",i+1);
scanf("%d",&field[i]);
if(field[i] / 100 >= 1 )
{
field[i] = 0;
}
}
for ( i = 0; i<n; i++)
{
printf("\nfield[%d] = %d\n", i, field[i]);
}
for(i=0; i <= 5;i+=5)
{
for(j =i; j <n;j++)
{
printf("%d ",field[j]);
}
printf("\n");
}
return 0;
}
This part of your code can not be output in five columns
for(i=0; i <= 5;i+=5)
{
for(j =i; j <n;j++)
{
printf("%d ",field[j]);
}
printf("\n");
}
So if you change this, it will be executed
for(i=0; i <n;i+=5)
{
for(j =i; j <i+5;j++)
{
printf("%d ",field[j]);
}
printf("\n");
}
I hope this code will be help.
if i am wrong, please tell me and give a chance.
I want to help you and be recognized.
I am trying to create a grid of, for example, 4 rows and 4 columns.The dimension of the grid is n*n size. I have tried the following piece of code which is working fine for 3 rows only as I am trying to print 4*4 grid. But the last grid (4th is this case) is never printed. I mean as soon as the 3rd grid is printed the loop exits. I would appreciate if anyone help me to figure out why it is taking only 3 rows with 4 columns rather than 4 rows with 4 columns? Here is what I have tried so far,
void main()
{
int n, i, j;
scanf("%d", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
}
}
This is a very quick hack to get your code working, as I believe you expect. Including the \n in scanf is probably not the best way of doing this, please see this answer:
int n, i, j;
scanf("%d\n", &n);
char grid[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (grid[i][j] == '9')
printf("X");
else
printf("%c", grid[i][j]);
}
printf("\n");
}
Using this as input:
4
1234234534564567
This is the output:
1234
2345
3456
4567
The line
scanf("%c", ...)
will also read any newline chars typed, including the one following the previous
scanf("%d", ...)
So if you enter each line's data followed by a newline, you will have read 1 + 3 * 5 = 16 characters after the third line.
I suggest you input four strings instead, and copy each character to the array, using scanf("%s", ...). That way, all whitespace will be ignored (except the final newline will remain in the input buffer).