C program array takes more input than it should - c

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

Related

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

Is there a way to add multiple values into an array in one command prompt?

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

Sorting inputted integers into odd and even arrays

I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

for loop resulting in undefined behaviour c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!
In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);
The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);
There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}

Using Scanf for Storing Input in 2d Arrays

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++;
}

Resources