Using Scanf for Storing Input in 2d Arrays - c

I want to scan input and save it in a square 2d array.
The first two digits are saved in seperate variables, the first digit is a target number (irrelevant here), the second digit gets saved in variable m, i.e. m = 5 in this case. m is the number of rows/colums of the square matrix. The rest of the input should be saved in the array.
For this particular input, I get a segmentation-fault and random numbers are printed on the screen.
I used some printf statements to trace where things go wrong, and I noticed that the index i in the first loop jumped from 2 to 11 in one scenario, for other input it jumped to 33.
Thanks for your help! I hope I am not missing an obvious mistake.
Input: (each row is seperated by the previous by pressing enter.)
42 5
0 3 7 9 10
9 13 20 5 20
12 11 33 0 12
17 39 22 3 18
My code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* arv[]){
int target; // for later processing, irrelevant here
int m; // m = #rows and #columns of array
int array[m][m];
scanf("%d %d", &target, &m);
int i, k;
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
scanf("%d", &(array[i][k])); // save value in array.
}
}
// the problem occurs before this point.
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
printf("%2d", array[i][k]); // print array.
}
printf("\n");
}
return 0;
}

You have not initialized the value of m before creating array[m][m]. Without initializing, the value of m can be anything.
Change:
int array[m][m];
scanf("%d %d", &target, &m);
to
scanf("%d %d", &target, &m);
int array[m][m];

This is the place where you messed up.
int m;
int array[m][m];
Here ,m is uninitialized and you are creating an array of m*m elements. You need m initialized before the declaration of the array. So move the array declaration after the scanf just after it so that m gets initialized before you declare the array.

#innclude <stdio.h>
int i, j;
int t[5][5];
i=0;
j=0;
while(i < 5)
{
j = 0;
while (j < 5)
{
scanf("%d", &(t[i][j++]));
}
i++;
}

Related

Getting inputs with scanf for an array

Just getting to learn C better and I'm playing with arrays.
I would like to enter my phone number into an array like this:
#include <stdio.h>
int main()
{
int phoneNum[10];
for (int i = 0; i < sizeof(phoneNum); i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
return 0;
}
This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:
int phoneNum[10];
printf("%lu", sizeof(phoneNum));
which incredibly gives me the result of 40 even though I initialized it to be 10 (?).
I have three questions:
Why is the result 40 and not 10 in sizeof(phoneNum) ?
How can I add elements in an array successfully with scanf in the above manner?
If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)
sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.
#include <stdio.h>
int main()
{
int phoneNum[10] = {0};
const size_t size = sizeof(phoneNum) / sizeof(int);
for (int i = 0; i < size; i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
for(int i = 0; i < size; ++i)
{
printf("\r\n %i \n", phoneNum[i]);
}
return 0;
}
sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.
#include <stdio.h>
#define SIZE 10
int main()
{
int phoneNum[SIZE];
for (int i = 0; i < SIZE; i++)
{
//Do Something
}
}
Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.

how to find sum of each value of column in multidimensional array

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");
}

how to continously scan for the amount of numbers inside of an array

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]);
}
}

C program array takes more input than it should

I was just playing around and i created a two D array in C of 3 rows and three columns and set a nested for loops to scan the elements.
Now, a three by three matrix has Nine elements but this code is taking 10 inputs(even the for loop is running only 9 times) How is it happening???
#include <stdio.h>
int main(){
int array[3][3];
int i,j;
for(i = 0; i < 3; ++i){
for(j = 0; j < 3; ++j){
printf("i = %d j = %d\n",i,j);
scanf(" %d ",&array[i][j]);
printf("i = %d j = %d\n",i,j);
}
}
scanf(" %d " --> scanf("%d"
Probably , the space after %d results in scanf waiting for another input. So, remove the space and it should work fine.
scanf("%d ",&array[i][j]) ----> scanf("%d",&array[i][j])
this might help resolving it

Printing an array using a pointer which has the address to its first element

I was playing around making different programs to learn how a pointer, arrays and the name of an array are related. I was getting all the answers till this simple program gave me an unexpected output.
Here I have taken an array input through a function, returned the address of its first variable to a pointer and then tried to use the pointer to print the array.Some thing went wrong and I Didnt get the output i was hoping for. Can someone tell me whats wrong with my code?
#include<stdio.h>
#include<stdlib.h>
int n;
int* InputArray()
{
printf("\nFucntion InputArray active\nPlease Enter the dimesnion (max 100): ");
scanf("%d",&n);
printf("\nAn array of %dx%d will be inputed and printed\n",n,n);
static int A[100][100];
int i=0,j=0;
for( i=0;i<n;i++)
{
printf("\n");
for( j=0;j<n;j++)
{printf("\nEnter the %d,%d element:",i,j);
scanf("%d",&A[i][j]);
}
}
//view the array
i=0,j=0;
for( i=0;i<n;i++)
{
printf("\n");
for( j=0;j<n;j++)
{printf("%d",A[i][j]);
}
}
return A;
}
int main()
{
int *AdrAry;
AdrAry=InputArray();
printf("\nDisplayig the array using its pointer declared ,"
"\nin the main\n");
int i,j;
printf("\n");
//Outputting array using pointer
for( j=0;j<n*n;j++)
printf("%d\t",*(AdrAry+j));
return 0;
}
I get the following output ( Observe the array output by the pointer not in sync with the declared array )
Fucntion InputArray active
Please Enter the dimesnion (max 100): 2
An array of 2x2 will be inputed and printed
Enter the 0,0 element:1
Enter the 0,1 element:2
Enter the 1,0 element:3
Enter the 1,1 element:4
12
34
Displayig the array using its pointer declared ,
in the main
1 2 0 0
Your 2D array is 100 x 100, so when you use AdrAry+j you print the first line only.
This should be:
for(i = 0; i < n; ++i)
for(j = 0; j < n; ++j)
printf("%d\t", *(AdrAry + (100 * i + j)));

Resources