User input from one line into multi dimention array - c

So i have this example:
3 4 6 11 4 6 38 7 6 9
I need to get from user several numbers and create multi dimension array.
The first number N (3 in my example) mean that my array (or matrix) will contain N² value and insert all this numbers (the next 9 values) into my array.
So first i need to define the array according my first value (3 in my example) and create my array:
int a[3][3];
The catch here is that i need to get all my input in a single line so i cannot use this:
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}

scanf reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
scanf will store whole the input from stdin, so it really does not matter if it is in single line or not. The way for your code is just, simply ask user for dimensions and create the variable of the given dimension and fill each value with a scanf.
There are 3 ways to do it :
If your compiler supports variable length array:
int size,i,j;
scanf("%d",&size);
int matrix[size][size];
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
Does not support variable length array: (using array of pointers)
int size,i,j;
scanf("%d",&size);
int **matrix;
matrix = (int **)malloc(sizeof(int *) * size);
for(i=0;i<size;i++)
{
matrix[i] = (int *)malloc(sizeof(int) * size);
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
This looks easy but the way is very poor as it is not actually an 2D array but an array of pointers. hence, I suggest to use the 3rd way if your compiler does not support variable length array.
Using malloc: (with pointer)
Create Array of integers like:
int size;
scanf("%d",&size);
int *matrix;
matrix = (int *) malloc( sizeof(int) * size * size );
Now, to fill or get the values of the Array you need to traverse to the particular value.
to fill:
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (matrix + i*(size) + j));
}
}
to iterate: (print in this case)
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d " ,*(matrix+ i*size + j) );
}
printf("\n");
}
Note: It is very important to constrain the input and check whether it lies in some fixed range or not. for ex: ( 0 < size < 100). It is very simple and you can do it yourself. I have answered the important parts only :)

To begin with, you can't store 10 numbers in a 3x3 matrix. Always make sure your specification makes sense before you start programming.
Taking the input is trivial, just use a nested loop to control where the read input ends up in your matrix. Example with a fixed array size:
#include <stdio.h>
#include <stdlib.h>
#define x 3
#define y 3
int main (void)
{
int arr[x][y];
printf("Enter %d numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
(Note that this leaves a whole lot of junk like line feed characters behind in stdin. There's also no buffer overflow protection. See How to read / parse input in C? The FAQ for examples of how to read input properly.)
If you need a variable size matrix, you can use variable length arrays (VLA):
size_t x = 3; // some run-time value
size_t y = 3; // some run-time value
int arr[x][y];
... // then same code as above
Alternatively, you can use a dynamically allocated 2D array:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int (*arr)[y] = malloc( sizeof(int[x][y]) );
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
free(arr);
return 0;
}
Alternatively, if your compiler is from the Jurassic period, you can use old style "mangled" 2D arrays:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int* mangled = malloc(x * y * sizeof *mangled);
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &mangled[i*x + j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", mangled[i*x + j]);
}
printf("\n");
}
free(mangled);
return 0;
}
The above 4 alternatives are the only alternatives. You should not use "pointer-to-pointer look-up tables", there is absolutely no need for them here. Unfortunately, lots of bad books and bad teachers spread that technique. See Correctly allocating multi-dimensional arrays.

Try this:
int** InitMatrix()
{
int** matrix = NULL;
int n;
if (scanf("%d", &n) > 0 && n > 0)
{
matrix = malloc(n * sizeof(int*));
for (int i = 0; i < n; i++)
{
matrix[i] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
{
if (scanf("%d", &matrix[i][j]) == 0)
{
// user input error; decide what to do here
}
}
}
}
else
{
// user input error; decide what to do here
}
return matrix;
}

Related

How to for loop an array then put elements into a list format?

I'm writing a program which scanf integers and printf in double.
Here is my code:
int main(void) {
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
for(int i=0;i<arraySize;i++) scanf("%lf", &vector[i]);
for(int a=0;a<arraySize;a++) printf("VECTORS:[%lf]",vector[a]);
}
Since I need to for loop every element in the array then printf all of them one by one.
this is the output I had:
VECTORS:[1.000000] VECTORS:[2.000000] VECTORS:[3.000000]
How can I change the format of the printf function and get ouput like this:
VECTOR: [ 1.000, 2.000, 3.000 ]
Your one major mistake is your array size. I know your compiler won't issue any warning but this is not any feature which language provide so size must be a
constant numerical value or const expression.
So in short you can't create array After asking size from user. This is completely wrong.
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
You must make size const. If you want less values than the declared size you can decrease the no of times for loop will run but you can't decide array size as inputted by user.
const int size = 10; // this is how your size should be. Even your compiler allowed VLA you should not try this. size of arrays must be constant.
int main()
{
unsigned int i,s;
int arr[size];
printf ("Enter the size of array.");
scanf("%d",&s);
for(i = 0 ; i<s;i++){
scanf("%d",&arr[i]);
}
for(i = 0 ; i<s;i++){
arr[i] = arr[i]*arr[i];
}
for(i = 0 ; i<s;i++){
printf("%d",arr[i]);
}
}
Print VECTOR once then loop over all the vectors and output them in the desired format.
const int size = 10;
int main(void) {
double vector[size];
for(int i=0;i<size;i++)
scanf("%lf", &vector[i]);
printf("VECTOR: [ ");
for(int a=0;a<size;a++){
printf("%lf", vector[a]);
if(i < size - 1)
printf(", ");
}
printf(" ]");
}
You need to allocate memory dynamically to use it.
Use the printf in the code below to define precision.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arraySize = 0;
scanf("%d",&arraySize);
double *vector = (double *) calloc(arraySize, sizeof(double));
for(int i=0; i<arraySize; i++) {
scanf("%lf", &vector[i]);
}
printf("VECTORS:[");
int a;
for(a=0;a<arraySize;a++) {
printf(" %.3lf",vector[a]);
if (a<(arraySize-1)) {
printf(",");
} else {
printf(" ");
}
}
printf("]");
}
Change your for loop to take 3 elements at once.
for(a=0;a<arraySize;a+=3) {
printf("VECTORS:[%lf", vector[a]);
if (a+1 < arraySize) printf(", %lf", vector[a+1]);
if (a+2 < arraySize) printf(", %lf", vector[a+2]);
printf("]\n");
}

2D Array elements changing after they are set

The program below is meant to print a square grid of integers based on the dimension which is inputted by the user (as part of the harvard cs50 course on edx).
The array is being initialized correctly, but when it comes to printing it out, the last column always prints incorrectly. I tried debugging by putting 2 printf statements in the innermost for loop of the init() function.
It seems that after the outermost loop runs once, the entry in the last column gets decremented by one, although it was correct just before this.
Why is this happening? Shouldn't it print correctly?
#include <stdio.h>
main()
{
void init(int dim, int arr[dim-1][dim-1]);
int dim;
printf("Enter board dimension(max 10): ");
scanf("%d", &dim);
int arr[dim-1][dim-1];
init(dim, arr);
int i,j;
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
printf("%2d ",arr[i][j]);
}
printf("\n");
}
}
void init(int dim, int arr[dim-1][dim-1])
{
int i,j,p;
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
arr[i][j] = (dim*dim-1)-i*dim-j;
}
for(p=0;p<dim;p++)
{
printf("%d ", arr[i][p]);
if(i>=1)
printf("%d ", arr[i-1][p]);
}
}
printf("\n");
if(dim%2==0)
{
arr[dim-1][dim-3] = 1;
arr[dim-1][dim-2] = 2;
}
}
EDIT: it should compile now
You define your array with a[dim - 1][dim - 1], which is one short of the desired dimension. If the user enters "4", you create a 3×3 array.
Your array is two-dimensional and of variable length. Therefore, you must pass the dimension alongside the array in functions, at least for the last dimension. You do this correctly, but the code in ´initbehaves as if the array werea[dim][dim], when it's actuallya[dim - 1][dim - 1]`.
Define the array with the actual dimension, dim and access the elements with indices 0 through dim - 1. This is usually done in a loop like this:
for (int i = 0; i < dim; i++) ...
Seeing >= or dim - 1 something similar should make you wary.
Your program now looks like this:
#include <stdio.h>
void init(int dim, int arr[dim-1][dim-1]);
void print(int dim, int arr[dim-1][dim-1]);
int main(void)
{
int dim;
printf("Enter board dimension: ");
scanf("%d", &dim);
int arr[dim][dim];
init(dim, arr);
print(dim, arr);
return 0;
}
void print(int dim, int arr[dim][dim])
{
int i,j;
for(i = 0; i < dim; i++) {
for(j = 0; j < dim; j++) {
printf("%2d ", arr[i][j]);
}
printf("\n");
}
}
void init(int dim, int arr[dim][dim])
{
int i, j;
for(i = 0; i < dim; i++) {
for(j = 0; j < dim; j++) {
int ii = dim - 1 - i;
int jj = dim - 1 - j;
arr[i][j] = ii*dim + jj;
}
}
}

Call a function that receives an array using a pointer

So I've this:
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int *pref = malloc(workers * sizeof(int));
if (pref == NULL)
return -1;
fillPreferences(pref, workers);
return 0;
}
I want now to fill the "pref" 2d array in this function:
void fillPreferences(int pref[][], int size)
{
for (int i=0;i<size;i++)
{
for (int j=0;j<size;j++)
{
scanf(" %d", &pref[i][j]);
}
}
}
It doesn't work, probably because I'm using the pointer wrong. How can I use malloc and then call a function and receive the values in the 2d array by doing pref[i][j]? (Note that I'm not looking to do something like scanf(..., &pref+i) or whatever. I need to actually use that 2d array.
Thanks :)
When you write a[i], it is turned into *(a+i). That is, a[i] accesses the memory by a+i address (well, it is a+i*sizeof(element) even).
As such, a[i][j] means *(*(a+i)+j). Two memory accesses. For this to work, your a should be an array of arrays. That is, you need to malloc its elements first and then malloc a memory to hold them.
In your particular case, i doubt you need it. What you need is make it 1D-array (which is it already) and calculate index from your two indices in whatever fashion you wish.
Your pref array is 1D so you can make it in this way:
#include <stdio.h>
#include <stdlib.h>
void fillPreferences(int **pref, int size)
{
int prefNum=0;
for (int i=0;i<size;i++)
{
puts("Number of preferences");
scanf("%d",&prefNum);
pref[i]=malloc(sizeof(int)*prefNum);
puts("Enter preferences");
for(int j=0;j<prefNum;j++){
scanf(" %d", &pref[i][j]);
}
}
}
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int **pref = malloc(workers * sizeof(int *));
if (pref == NULL)
return -1;
fillPreferences(pref, workers);
// Show values
printf("%d %d %d",pref[0][0],pref[1][0],pref[2][0]);
return 0;
}
You allocate memory for a 1D array, but the function you have is designed to accept a 2D array and fill it (although the function definition is incorrect and won't compile).
Corrected code:
#include <stdio.h>
#include <stdlib.h>
void fillPreferences(int** pref, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
scanf("%d", &pref[i][j]);
}
}
}
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int **pref = malloc(workers * sizeof(int*));
if (pref == NULL)
return -1;
for(int i = 0; i < workers; i++)
{
pref[i] = malloc(workers * sizeof(int));
if(pref[i] == NULL)
{
for(int j = 0; j < i; j++)
free(pref[j]);
free(pref);
return -1;
}
fillPreferences(pref, workers);
/* Don't forget to `free` everything after its use! */
return 0;
}

How to create a 2d array, the dimensions of which are specified by the user? (in C)

Here is my try. I am not totally sure about my manipulations with the pointer. Maybe this is why I am wrong, maybe there is some other case. I want to take the dimensions from the user and create a square matrix, make some manipulations with its elements, and display the original and results to the user. Last time I accomplished this by creating a 100x100 array, and specifying the end of each line, and end of lines by constants. Then I would print all the elements up to this constant. But it does not seem to be right to create a 100x100 array for 4x4 matrices. I could create a smaller array, but this does not seem to be the right solution to the problem. Is there a way in C to create a 2d array exactly the size specified by the users (it will be a square array). Thanks
#include <stdio.h>
#include <stdlib.h>
double * createMatrix(int dimentions);
void drawMatrix(double * matrix);
int main(void)
{
int n, i, j;
system("cls");
system("color 70");
system("pause");
puts("Enter the matrix's dimension");
scanf("%i", &n);
double * pmatrix = createMatrix(n);
for (i = 0; i < n; ++j)
for (j = 0; j < n; ++j)
{
printf("A%i%i: ", i + 1, j + 1);
scanf("%lf", pmatrix[i][j]);
getchar();
}
for (i = 0; i < n; ++i)
{
putchar('\n');
for (j = 0; j < n; ++j)
printf(" %lf ", &pmatrix[i][j]);
}
system("color 08");
return 0;
}
double * createMatrix(int n)
{
const int N = n;
const int N1 = N;
double matrix[N][N];
double * pmatrix = matrix;
return pmatrix;
}
You can create a matrix directly; you don't need a function for that. Replace the code
double * pmatrix = createMatrix(n);
by the regular way of declaring a 2-D array:
double matrix[n][n];
One more way of doing it using pointers.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
double **pmatrix;
int rowsize, colsize, i, j;
printf("Enter the number of rows: ");
scanf("%d",&rowsize);
printf("Enter the number of columns: ");
scanf("%d",&colsize);
//Allocate memory for 2D array
pmatrix = malloc(rowsize*sizeof(double*));
for(i=0;i<rowsize;i++)
{
pmatrix[i] = malloc(colsize*sizeof(int));
}
//Accepting the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("A %i %i: ", i + 1, j + 1);
scanf("%lf",&pmatrix[i][j]);
}
}
//Printing the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("%lf\t",pmatrix[i][j]);
}
printf("\n");
}
//Free the memory
for(i=0;i<rowsize;i++)
free(pmatrix[i]);
free(pmatrix);
return 0;
}

My 2d array is taking one extra element

I am trying to input 2d array from user, my array size is 6, but I am bale to input 7 elements. What is the error here? can you please also tell me how to input a 2d array from user using single pointer.
#include <stdio.h>
int main()
{
int a[2][3] = {0};
int i=0,j=0,l=0;
printf("enter 2d");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d\n",&a[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\n",a[i][j]);
}
}
return 0;
}
Here's my output:
./input2dusingsinglearray
enter 2d
1
2
3
4
5
6
7
1
2
3
4
5
6
The problem is with your scanf waiting for an extra intro, change to:
#include <stdio.h>
int main(void)
{
int a[2][3] = {0};
int i=0,j=0,l=0;
printf("enter 2d\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\n",a[i][j]);
}
}
return 0;
}
Also note that a 2d array must be initialized in this way:
int a[2][3] = {{0},{0}};
Turning your warnings on:
warning: missing braces around initializer [-Wmissing-braces]
Try using scanf("%d", &a[i][j]) instead of scanf("%d\n", &a[i][j]).
While the other answers are fine and correct, allow me to add my solution as well
#include <stdio.h>
#include <stdlib.h>
int main(){
size_t rows = 2;
size_t columns = 3;
int* matrix = (int *) malloc( rows * columns * sizeof(int));
printf("insert into 2d matrix[%d][%d]:\n", rows, columns);
int i = 0, j = 0;
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
scanf("%d", (matrix + (i * columns) + j));
}
}
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
printf("matrix[%d][%d] => %d\n", i, j, *(matrix + (i * columns) + j));
}
}
free(matrix);
return 0;
}
It dynamically allocate memory for 2d array and it can be an elegant solution if you want to pass pointer to a function.
I've faced the same problem yesterday and found that when we use extra space or any other thing it wants extra input. Then I've used the scanf function like down below.
scanf("%d",&a[i][j]);

Resources