Hi I'm trying to write a code for user input matrix size and values. I got the bit about setting the matrix size and value, but I want to read in one row at a time so that I don't have to press enter every time after a single value input. This is my code so far. Thanks.
int row, col, i, j;
int mat[10][10];
printf("Enter number of rows: ");
scanf("%d", &row);
printf("Enter number of columns: ");
scanf("%d", &col);
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
scanf("%d", &mat[i][j]);
}
}
printf("\nHere is your matrix:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
I want to read in one row at a time so that I don't have to press enter every time
The code you listed can work this way! That's how scanf works.
You CAN press an Enter once each number or once each row(you should use space or tab to delimit numbers) or even after you input the whole matrix, just try it!
In C Memory is allocated continuously
The values will be stored in the array row wise so use space instead of new line it will work
Even if you type all elements on one line separated by space it will store row wise
so if
rows=3 col=3
i/p= 1 2 3 4 5 6 7 8 9
matrix will be
1 2 3
4 5 6
7 8 9
Related
I am trying to code a program that asks the user for the # of rows and columns and generates a 2d array (a matrix) corresponding to their input. I then ask for a second matrix (same dimensions), then I do some math on the 2 matrices. I'm stuck on how to use the scanf function to get the user-inputted matrix. According to the guidelines, the user input will be in the shape of the matrix itself, ex if it is a 2x2 matrix the user enters:
12 10 (then on the next line)
10 10
How do I use the scanf function appropriately to copy this matrix into the 2d array that I've created? I know that you can do scanf("%d %d %d", &int1, &int2, &int3), but I don't know if this will work for a user-determined matrix, since the length could be 2, 10, even a 100 (which is max length for this problem).
#include <stdio.h>
int main(void) {
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
/*User enters matrix in the form:
12 10
10 10
*/
printf("Enter Matrix A\n");
for(int i=0; i<sizeof(matrixA); i++){
for(int j=0; j<sizeof(matrixA[i]);i++){
scanf("%d ",&matrixA[i][j]);
}
}
//to see if scanf worked
for (int i = 0; i<sizeof(matrixA); i++) {
for(int j=0; j<sizeof(matrixA[i]);i++) {
matrixA[i][j] = '.';
printf("%c ",matrixA[i][j]);
}
printf("\n");
}
int matrixB[r][c];
printf("Enter Matrix B\n");
return 0;
}
You are right that
scanf( "%d %d %d", &int1, &int2, &int3 );
will only work if the number of parameters is fixed at compile-time. It cannot be changed at run-time.
Your idea of calling
scanf("%d ",&matrixA[i][j]);
in a loop instead is correct, in principle. However, you should not have a space character in the format string, as this will cause scanf to continue to read input from the input stream, and it will only return after it has encountered a non-whitespace character. This is usually not what you want.
Also, the line
for(int i=0; i<sizeof(matrixA); i++){
is wrong, because sizeof(matrixA) is the size of the array in bytes. Since you instead want to get the number of elements in the outer array, you could write sizeof matrixA / sizeof *matrixA instead. (The parentheses are only necessary when referring to types, not variables.) However, in this case, it would be easier to simply use r instead.
The line
for(int j=0; j<sizeof(matrixA[i]);i++){
is wrong. You probably intended to write j++ instead of i++.
Also, when printing variables of type int with printf, you should usually use %d instead of %c, because otherwise the value may be truncated if the value is higher than 127.
It is unclear what the line
matrixA[i][j] = '.';
is supposed to accomplish, as this will overwrite the previous input of scanf (assuming that you fix your loop as described above).
After fixing all of the issues mentioned above, your code should look like this:
#include <stdio.h>
int main(void)
{
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
printf("Enter Matrix A:\n");
for ( int i=0; i < r; i++ )
for( int j=0; j < c; j++ )
scanf( "%d", &matrixA[i][j] );
//to see if scanf worked
printf( "Input complete, the array contents are:\n" );
for ( int i=0; i < r; i++ )
{
for( int j=0; j < c; j++ )
printf( "%d ",matrixA[i][j] );
printf( "\n" );
}
return 0;
}
This program has the following behavior:
Please enter the number of rows : 4
Please enter the number of columns : 4
Enter Matrix A:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input complete, the array contents are:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
POSIX-specific answer
Well, you don't.
There are two ways to get that done:
Slice stdin into rows by the '\n' character n times; later slice every row in n columns by ' ' the whitespace. getline and strtok come in handy here.
The other approach is more efficient and as usual more complicated: rather than slicing into rows first, you iterative cut-off cols, counting them, and when count == n comes true, you expect '\n' to be there thus ending another line. I wouldn't suggest this approach.
So roughly your codes looks something like:
ssize_t nread;
for (sizet_t i = 0; i < n; i++) {
char *line = NULL;
if ((nread = getline(&line, &len, stream)) != -1) {
fprintf(stderr, "Bad format: %il-th line expected.", i + );
exit(EXIT_FAILURE);
}
char* token = strtok(line, " ");
for (size_t ii = 1 /* because you've already cut-off the first token */; i < n; ii++) {
token = strtok(NULL, " ");
}
}
Of course, you have to parse your char * tokens, but that is something I leave to you as an exercise. It also quite sloppy and does not do any sort of validation a production code is expected to do.
sorry, im still try to figure out about multiple repetition and array and i need help to find sum of each value of column in multidimensional array.
so i have this input :
2 -> number of tc
3 -> size of array
1 2 3
4 5 6 -> all value of array
7 8 9
4 -> size of array
1 2 3 4
5 6 7 8 -> value of array
9 0 1 2
3 4 5 6
and the output will be :
Case#1: 12 15 18
Case#2: 18 12 16 20
and here is my code :
int n,m;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&m);
int o[m][m],sum[m][m];
for(int i=1;i<=m;i++){
for(int j=1;j<=m;j++){
scanf("%d",&o[i][j]);
sum[i][j]=o[i][j]+o[i+1][j+1];
}
}
for(int i=1;i<=m;i++){
for(int j=1;j<=m;j++){
printf("Case #%d: %d ",i,sum[i][j]);
}
printf("\n");
}
}
return 0;
}
First the code :
#include <stdio.h>
int main () {
int cases;
printf ("\nCases Count? : ");
scanf ("%d", &cases);
for (int cid = 0; cid < cases; ++cid) {
int size;
printf ("\nMatrix Size : ");
scanf ("%d", &size);
long sum [size]; // if long has more space than int on your machine, else use long long
for (int col = 0; col < size; ++col) // reset sums before next case
sum[col] = 0;
// we don't need to store matrix, as we're not re-using it
for (int row = 0; row < size; ++row) {
for (int col = 0; col < size; ++col) {
int value;
scanf ("%d", &value);
sum[col] += value; // add the value to respective column total
}
}
printf ("Case #%d: ", cid + 1);
for (int col = 0; col < size; ++col)
printf ("%ld ", sum[col]);
printf ("\n");
}
return 0;
}
Warning: scanf() fails if you input a string instead of numbers. scanf() usage. Lookup how to use fgets() & parse inputs to have more control.
There is no prize for using bare minimum variable names. Use concise yet meaningful variable names, even if you're testing something.
Enable all compiler warnings. For GCC an alias something like alias mygcc='gcc -Wall -Wextra -pedantic -g3 -O2 -fsanitize=address,undefined,leak -Wshadow'.
I have a few suggestions to help you along. First, the first, second, and fourth for loops use the same indexing variable i. This will cause issues with the first for loop as the variable i is being changed by the others. I suggest you first create a program that only works with a single matrix then, once it works correctly, expand it to handle multiple matrices. This will reduce the number of for loops you have to manage while figuring out the indexing. Second, the sum array doesn't have the correct size. It looks like it should be sum[n][m] instead of sum[m][m]. Lastly, to get the output you want, you should move the output for loop outside of the first for loop. Like this:
int n,m;
scanf("%d",&n);
for(int i=1;i<=n;i++){
...
for(int i=1;i<=m;i++){
...
}
}
for(int i=1;i<=m;i++){
for(int j=1;j<=m;j++){
printf("Case #%d: %d ",i,sum[i][j]);
}
printf("\n");
}
I am trying to scanf 5 numbers into an array in one command line prompt. I know how to store a value one by one into an array, but in this case I am trying to store 5 values in a line. I know how to hard code it when the limit is clear, but I want to code it based on a user inputted limit.
for example (hard code):
int arr[5];
scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
for (i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
would give me the values of arr[0] arr[1] arr[2] arr[3] arr[4].
BUT what if the size of aaa is defined by users, or defined by a macro that allows changes? How do you not hard code it?
#define MAX 10
int arr[MAX];
or
printf("what is the limit? : ");
scanf("%d", &limit);
int arr[limit];
I tried using a for loop but it doesn't work.
for(i=0;i<MAX; i++){
scanf("%d %d %d %d %d\n", &aaa[i]); //I want user to input 5 numbers in one line, but this format doesnt work.
}
To conclude/clarify my question.
I want user to input 5 numbers in one line. for example : 1 2 3 4 5 with a space in between. and I want it stored at arr[0] arr[1] arr[2] arr[3] arr[4]. Is there a way to not hard code this?
Help would be greatly appreciated! Thanks!
You want this:
#include <stdio.h>
int main()
{
int arr[5];
printf("Enter 5 numbers separated by space then press Enter\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
}
Execution:
Enter 5 numbers separated by space then press Enter
1 2 3 4 5
1 2 3 4 5
You need to read inputs in the loop as below.
for(i=0;i<MAX; i++) {
scanf("%d", &aaa[i]);
}
I currently am having a small trouble in my code, I am supposed to make a program that adds / sums all numbers inside of an array, while I have no problem in doing that, I currently have a problem with the part in which you are supposed to scan the numbers to be put in the array, here are the example of the input
3
5
1 2 3 4 5
8
1 2 3 4 5 6 7 8
9
1 2 3 4 5 6 7 8 9
What this means is that, the user inputs number "3" as it means to create 3 arrays, the number "5" afterward means to put 5 numbers inside of the array (1 2 3 4 5), after the user has inputted the numbers inside of an array, the user inputs "8" which means to make another array consisting of 8 numbers, and then putting numbers into the array again, and so on.
However I am having a problem in which after inputting all the numbers in the array that consists of 5 number, the program instead inputs 5 number into another array again (instead of asking the amount of numbers to be put inside of another array), so instead the number "8 1 2 3 4" gets inputted in another array, and I did not know which part I did wrong.
Here are my C code :
#include <stdio.h>
int main(){
int x, y;
int i;
int n;
int c=1;
int count=0;
int sum=0;
scanf("%d", &y); //this determines the amount of array to be inputted
scanf("%d", &x); //this determines the amount of numbers to be inputted inside of an array
int line[x];
for(int i=0; i<y; i++){
sum=0;
for(int i=0; i<x; i++){
scanf("%d", &line[i]); //scan number for the array
sum += line[i];
}
printf("Case #%d: %d\n", c, sum);//output of all sum
c++;
}
}
You need to read the size for each array - currently you only read it once.
e.g.:
int numLines;
scanf("%d", &numLines);
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
int line[numNumbers];
for(int i = 0; i < numNumbers; i++) {
scanf("%d", &line[i]);
}
}
Additionally you can avoid storing the individual numbers, since you're only interested in the sum, e.g.:
int sum = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sum += number;
}
Also you could defer outputting the sums until all inputs have been processed, so it doesn't visually get interleaved into the input.
This would be a possible way to write that program: godbolt
#include <stdio.h>
int main() {
// get the number of arrays we need to read
int numLines;
scanf("%d", &numLines);
// The sums of each array
int sums[numLines];
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
// sum up all the numbers of the array
sums[lineIdx] = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sums[lineIdx] += number;
}
}
// after all arrays have been entered,
// output the sums for each case:
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
printf("Case #%d: %d\n", lineIdx, sums[lineIdx]);
}
}
The goal is to print the transpose of the 'Matrix'.
To create square matrix, I got 'row' from the keyboard.
row is same with column so I only declared 'row'.
the problem I need help is right below ↓
/*input*/
5 4 1
9 0 1
6 5 7
/*output I want*/
5 9 6
4 0 5
1 1 7
/*wrong output I get*/
0 4 -30838770
0 7 2
0 5 7
And here is my code. Matrix in each function must be called by reference. I also want to know if I got it right.
//code start
int Generate(int row, int (*Matrix)[row])
{
srand(time(NULL)); //make random number
int i, j;
printf("Matrix = ");
for(i=0; i<row; i++){
for(j=0; j<row; j++){
Matrix[i][j] = (rand() % 10); //insert random number from 0 to 10
printf("%d ", Matrix[i][j]); //print matrix before transposing
}
printf("\n");
}
return 0;
}
void Transpose(int row, int (*Matrix)[row])
{
int i, j;
for(i=0; i<row; i++){
for(j=0; j<row; j++){
int transpose[i][j];
transpose[i][j] = Matrix[j][i];
printf("%d ", transpose[i][j]);
}
printf("\n");
}
}
int main() {
int input; //for switch case
int row = 0; //row has to be 2 or 3
int Matrix[row][row]; //2d array. largest index should be Matrix [row-1][row-1]
while(1){
scanf("%d", &input);
switch(input){
case 1: // Generate random square matrix
scanf("%d", &row); //insert row
Generate(row, Matrix);
break;
case 2: //transpose matrix
Transpose(row, Matrix);
break;
default:
return 0;
}
}
}
//code end
I'm new to this community so I'm not sure I gave you all the information needed.
Please let me know the lines you don't understand because I really want to get this code work.
I'm waiting for your help!
Your program is trying to print the transpose, so you don't need to store anything. remove all the stuff with transpose[i][j], and just print Matrix[j][i]. As pointed out in the comments, you are allocating (on the stack) a new matrix of shape ixj at each iteration, which makes no sense.