How to fill a 2D array in C with user input values? - c

Note: This is a homework question.
Use FOR construction to fill 2D board with values that were given by
user. The program asks for board size n, m and then it asks for each
board value.
My try
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i = scanf("%d",&i);
printf("Enter the number of rows");
int y = scanf("%d",&y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for(b=0; b<y; b++){
int r[a][b] = scanf("%d",&a,&b); //bug
}
}
}
Bug: c:13 variable-sized object may not be initialized
EDIT:
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i;
scanf("%d", &i);
printf("Enter the number of rows");
int y;
scanf("%d", &y);
int r[i][y];
int a;
int b;
for (a=0; a<i; a++){
for (b=0; b<y; b++){
scanf("%d",&r[a][b]);
}
}
}

scanf takes the address of the variable that is being read and returns the number of items read. It does not return the value read.
Replace
int i = scanf("%d",&i);
int y = scanf("%d",&y);
by
scanf("%d",&i);
scanf("%d",&y);
and
int r[a][b] = scanf("%d",&a,&b);
by
scanf("%d",&r[a][b]);
EDIT:
You are using variable length array (VLA) in your program:
int r[i][y];
as i and y are not constants and are variables. VLA are a C99 standard feature.

you have to allocate the 2D array dynamically cause you don't know it size in compilation.
replace
int r[i][y];
with
int *r = malloc(i*y*sizeof(int));
and when finish, add:
free(r);
*and also the SCANF errors, people already answered here.

First the return value of scanf isn't the value that was read from stdin, instead it is the number of input values scanf read.
Secondly, C does not allow creation of arrays by using variables. You have to first create one array by dynamically allocating it. And for each entry in the first array you have to create yet another array.
Don't forget to free the memory you allocate!

The use of scanf(%d, &var) is incorrect.
scanf reads from console an integer (this type is specified by its first paramenter %d) and stores it in the second parameter.
This second parameter must be a pointer, so an & is needed when your variable is not a pointer yet.
Therefore you should correct your code in this way:
int i;
scanf("%d",&i);
int y;
scanf("%d", &y);
And in your for loop
scanf("%d", &r[a][b]);

It doesn't print the message because of line buffering.
If you add \n to your strings (to start a new line), it might do what you expect:
printf("Enter the number of columns\n");
Alternatively, if you really want the user to type on the same line, you need to flush the buffer manually:
printf("Enter the number of columns");
fflush (stdout);

Related

Read a list of n numbers and make an array in C

So I want to take an input such as this:
The first input tells us the size of the array and the second line contains the numbers of array like this:
input:
3
1 2 3
And I want to make an array from the second input line with a size of from the first input line.
I currently have:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n;
scanf("%d", n);
int x[n];
int y[n];
}
But after which I get stumped.
If you have a VLA(Variable Length Array) supporting compiler(eg. GCC):
int n;
scanf("%d", &n);
int arr[n];
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
and if not,
int n;
scanf("%d", &n);
int *arr = malloc(n * sizeof(int));
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
This code uses the functionality of scanf to be able to take multiple delimited input.
If you have to take n inputs and not only set the size of arr to n, do this:
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &n[i]);
}
It should be apparent that VLA functionality lets you to make an array on the stack with a runtime value. Otherwise, you'll need to allocate it on the heap with malloc().
What if there are more than 3 numbers to scan. Do I need to add more
"%d" and arr[] or is there some way for it to work with any number of
numbers in the second line.
To address this point you can go with iterating over loop
for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
}

Print all inputted number by the user in C

I am trying to print all inputted number by the user using the code below but instead of printing all inputted numbers it only print the last number I inputted.
#include<stdio.h>
int display(int n, int a, int b)
{
printf("\n\nOrdered pairs are: ");
for(int j=0;j<n;j++)
{
printf("(%d,%d) ",a,b);
}
return 0;
}
int main()
{
int num,i,j,x,y;
printf("Total number of points: ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n\nPoint #%d: \n",i+1);
printf("x=");
scanf("%d",&x);
printf("y=");
scanf("%d",&y);
printf("Point #%d: (%d,%d)",i+1,x,y);
}
display(i,x,y);
return 0;
}
You don't have memory for storing more than 2 numbers (x and y) which are over-written during each iteration of the loop.
Perhaps you meant to use arrays, or dynamically allocated memory. This:
int x[100], y[100];
is one way, then you can store up to 100 numbers in each of the two arrays. Use array indexing when accessing.
Actually you are changing the value stored in x and y again and again and so, the previous values get destroyed and only the last value is stored. So you can you arrays (which are more easier to use) or you can even use structure (I would prefer to use arrays).

program returning garbage values even after declaring variables in c

how do i correct this
i didn't use structure intentionally
this is a program to input student's name, subject and marks.
in the last block, the array (subject+f) 's 1st subscript is returning garbage values while the rest subscript are returning desired result.
i have also posted the image of output as link.
#include<stdio.h>
#include<string.h>
int main()
{
int size,i,k,sub,a=0,reference;
int temp,sorted;
char temp_s[10];
char temp_sb[10];
printf("enter the size of class\n");
scanf("%d",&size);
printf("how many subjects are there?\n");
scanf("%d",&sub);
reference = sub;
char name[size][20];
char subject[size*sub][20];
int marks[sub*size];
int total,subtotal,retotal;
for(k=0;k<sub;k++)
{
printf("so what's the no. %d subject\n",k+1);
scanf(" %s",(subject[k]));
}
for(i=0;i<size;i++)
{
int j,k=0;
printf("Enter a name of student %d\n",i+1);
scanf(" %s",(name+i));
for(j=a;j<reference;j++)
{
printf("enter marks of %s\n",(subject[k]));
scanf("%d",(marks+j));
k++;
}
a=j;
reference=sub+j;
}
reference=sub;
a=0;
printf("\n list of students and marks:\n");
for(i=0;i<size;i++)
{
int j,f=0;
printf("%s\n",(name+i));
for(j=a;j<reference;j++)
{
printf("%s %d\n",(subject[f]),(marks[j]));
f++;
}
a=j;
reference=sub+j;
}
}
Besides the problem with length of names and subjects, this here is a major problem:
(subject+k)
You are probably misunderstanding the subject[k] and *(subject + k) equivalent.
The variable subject is an array of arrays. That means subject[i] is an array (of char and can be used as a zero-terminated string).
The expression (subject + k) is a pointer to the array in subject[k]. It's equal to &subject[k] which have the type char (*)[10]. It's can not be used as a zero-terminated string without dereferencing. So either use *(subject + k) or the simple, less-to-write and easier-to-read subject[k].
I think you also need to change
int marks[sub];
to
int marks[size * sub];
one mark for each subject for each student, correct?

scanf() is getting stuck on final use

I'm trying to use scanf to assign values to some integers but whichever scanner I put last will get suck as if it it wasn't seeing the new line. I've tried flushing the input buffer before every scan, but its hasn't helped. Do i need to malloc the pointers, even if they are being passed as the address of an existing variable out of function?
code:
void settings(int *x, int *y, int *l, int *m){
printf("Please enter the size of the game board (e.g. 3x6): ");
scanf("%dx%d",x,y);
printf("Please select the level of the game (0-9): ");
scanf("%d",l);
printf("Please enter the largest card value (1-99): ");
scanf("%d",m);
printf("Please enter the seed of the random number generator: (0-9999): ");
int s;
scanf("%d",&s);
srand(s);
return;}
Thanks
Actually, it should work.
Pay attention that your pointers should be initialized before the call, they can't be NULL:
int *x = (int *)malloc(sizeof(int));
int *y = (int *)malloc(sizeof(int));
int *l = (int *)malloc(sizeof(int));
int *m = (int *)malloc(sizeof(int));
settings(x,y,l,m);
No problem besides that...

Scan and sum using array in C

I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?

Resources