Nested for loop saving last input not whole input - c

I'm back again with that C question heh. So I'm trying to get the user to input a whole 2d array (size, values, everything), with VLA arrays (im using the latest compiler). Everything is fine up until I get the nested for loop, then it saves the last value into the array and ignored anything before it. I cannot seem to figure out how to fix my VLA to iterate through every element in the array and assign the value typed in by the user, all I get is it saving my last value into the whole array. Through some testing I've found that my problem is contained in my Inner loop of my nested for loop. EDIT: Through the help of Weather Vane, it was figured out that the array needs to be initialized after my x and y are saved, but now it saves my last value in the whole array and not every value typed. Here's my code snippet:
int x, y, row, col, a = 0;
//int NxM[x][y]; Moved
bool counter[10]; //I have 1 last part to code that involves this
printf("This program counts occurrences of digits 0 through 9 in an NxM
array.\n");
printf("Enter the size of the array (Row Column): ");
scanf("%d %d", &x, &y);
int NxM[x][y]; //Moved here.
for(row = 0; row < x; row++){
printf("Enter row %d: \n", a);
a++;
for(col = 0; col < y; col++){
scanf("%d ", &NxM[x][y]);//Why you only save 1 value >.<
}
}
(The reason I have my printf statement between my loops was to test where my looping problem was, and because I need my printf to look like Enter row 0 Enter row 1 etc..)

Related

Need help solving a problem with an array

Task: Calculate the 25 values of the function y = ax'2 + bx + c on the interval [e, f], save them in the array Y and find the minimum and maximum values in this array.
#include <stdio.h>
#include <math.h>
int main()
{
float Y[25];
int i;
int x=3,a,b,c;
double y = a*pow(x,2)+b*x+c;
printf("a = ", b);
scanf("%d", &a);
printf("b = ", a);
scanf("%d", &b);
printf("c = ", c);
scanf("%d", &c);
for(i=0;i<25;i++)
{
printf("%f",y); //output results, not needed
x++;
}
system("pause");
}
Problems:
Cant understand how can I use "interval [e,f]" here
Cant understand how to save values to array using C libraries
Cant understand how to write/make a cycle, which will find the
minimum and maximum values
Finally, dont know what exactly i need to do to solve task
You must first ask the user for the values of a, b, c or initialize those variables, and ask for the interval values of e, f, or initialize those variables.
Now you must calculate double interval= (f - e)/25.0 so you have the interval.
Then you must have a loop for (int i=0, double x=e; i<25; i++, x += interval) and calculate each value of the function. You can choose to store the result in an array (declare one at the top) or print them directly.
Problems:
Cant understand how can I use "interval [e,f]" here
(f-e) / 25(interval steps)
Cant understand how to save values to array using C libraries
You need to use some form of loop to traverse the array and save the result of your calculation at every interval step. Something like this:
for(int i = 0; i < SIZE; i++)
// SIZE in this case 25, so you traverse from 0-24 since arrays start 0
Cant understand how to write/make a cycle, which will find the minimum and maximum values
For both cases:
traverse the array with some form of loop and check every item e.g. (again) something like this: for(int i = 0; i < SIZE; i++)
For min:
Initialize a double value(key) with the first element of your array
Loop through your array searching for elements smaller than your initial key value.
if your array at position i is smaller than key, save key = array[i];
For max:
Initialize a double value(key) with 0;
Loop through your array searching for elements bigger than your initial key value.
if your array at position i is bigger than key, save key = array[i];
Finally, dont know what exactly i need to do to solve task
Initialize your variables(yourself or through user input)
Create a function that calculates a*x^2 + b*x + c n times for every step of your interval.
Create a function for min & max that loops through your array and returns the smallest/biggest value.
Thats pretty much it. I will refrain from posting code(for now), since this looks like an assignment to me and I am confident that you can write the code with the information #Paul Ogilvie & I have provided yourself. Good Luck
#include<stdio.h>
#include<math.h>
int main()
{
double y[25];
double x,a,b,c,e,f;
int i,j=0;
printf("Enter a:",&a);
scanf("%lf",&a);
printf("Enter b:",&b);
scanf("%lf",&b);
printf("Enter c:",&c);
scanf("%lf",&c);
printf("Starting Range:",&e);
scanf("%lf",&e);
printf("Ending Range:",&f);
scanf("%lf",&f);
for(i=e;i<=f;i++)
{
y[j++]=(a*pow(i,2))+(b*i)+c;
}
printf("\nThe Maximum element in the given interval is %lf",y[j-1]);
printf("\nThe Minimum element in the given interval is %lf",y[0]);
}
Good LUCK!

How to add the first number and last number of a series of number in C?

I am a beginner to C language and also computer programming. I have been trying to solve small problems to build up my skills. Recently, I am trying to solve a problem that says to take input that will decide the number of series it will have, and add the first and last number of a series. My code is not working and I have tried for hours. Can anyone help me solve it?
Here is what I have tried so far.
#include<stdio.h>
int main()
{
int a[4];
int x, y, z, num;
scanf("%d", &num);
for (x = 1; x <= num; x++) {
scanf("%d", &a[x]);
int add = a[0] + a[4];
printf("%d\n", a[x]);
}
return 0;
}
From from your description it seems clear that you should not care for the numbers in between the first and the last.
Since you want to only add the first and the last you should start by saving the first once you get it from input and then wait for the last number. This means that you don't need an array to save the rest of the numbers since you are not going to use them anyway.
We can make this work even without knowing the length of the series but since it is provided we are going to use it.
#include<stdio.h>
int main()
{
int first, last, num, x = 0;
scanf("%d", &num);
scanf("%d", &first);
last = first; //for the case of num=1
for (x = 1; x < num; x++) {
scanf("%d", &last);
}
int add = first + last;
printf("%d\n", add);
return 0;
}
What happens here is that after we read the value from num we immediately scan for the first number. Afterwards, we scan from the remaining num-1 numbers (notice how the for loop runs from 1 to num-1).
In each iteration we overwrite the "last" number we read and when the for loop finishes that last one in the series will actually be the last we read.
So with this input:
4 1 5 5 1
we get output:
2
Some notes: Notice how I have added a last = first after reading the first number. This is because in the case that num is 1 the for loop will never iterate (and even if it did there wouldn't be anything to read). For this reason, in the case that num is 1 it is reasonably assumed that the first number is also the last.
Also, I noticed some misconceptions on your code:
Remember that arrays in C start at 0 and not 1. So an array declared a[4] has positions a[0], a[1], a[2] and a[3]. Accessing a[4], if it works, will result in undefined behavior (eg. adding a number not in the input).
Worth noting (as pointed in a comment), is the fact that you declare your array for size 4 from the start, so you'll end up pretending the input is 4 numbers regardless of what it actually is. This would make sense only if you already knew the input size would be 4. Since you don't, you should declare it after you read the size.
Moreover, some you tried to add the result inside the for loop. That means you tried to add a[0]+a[3] to your result 4 times, 3 before you read a[3] and one after you read it. The correct way here is of course to try the addition after completing the input for loop (as has been pointed out in the comments).
I kinda get what you mean, and here is my atttempt at doing the task, according to the requirement. Hope this helps:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first, last, num, x=0;
int add=0;
printf("What is the num value?\n");//num value asked (basically the
index value)
scanf("%d", &num);//value for num is stored
printf("What is the first number?\n");
scanf("%d", &first);
if (num==1)
{
last=first;
}
else
{
for (x=1;x<num;x++)
{
printf("Enter number %d in the sequence:\n", x);
scanf("%d", &last);
}
add=(first+last);
printf("Sum of numbers equals:%d\n", add);
}
return 0;
}

Addition of sparse matrix using structure in c(triplet form)

I am currently doing a problem of addition of sparse matrices. I am making sparse matrix by using triplet form. The triplet form is made by using structure in c.
struct sparse
{
int row;
int col;
int val;
};
but while doing this sparse matrix problem I encountered a problem that my code only displays the correct sparse matrix when i am giving the indices of nonzero values in increasing order (eg. (0 1 3),(1 2 5),(2 2 7) etc)otherwise it is displaying incorrect matrix.for example if am giving input like (0 1 3),(2 2 7),(1 2 5) etc then it is displaying wrong matrix. How to solve this problem so that in any order of indices it will give correct output?
I have added my input and resulting output. I have done this for two sparse matrix.
#include<iostream>
#include<cstdio>
struct sparse
{
int row,col,val;
};
void readmat(sparse sp[])
{
printf("enter total number number of rows ,column of matrix and total
of nonzero values in this\n");
scanf("%d %d %d",&sp[0].row,&sp[0].col,&sp[0].val);
printf("now start entering the values by specifying index
position\n");
for(int i=1;i<=sp[0].val;i++)
scanf("%d %d %d",&sp[i].row,&sp[i].col,&sp[i].val);
}
void displaymat(sparse sp[])
{
int k=1;
for(int i=0;i<sp[0].row;i++)
{
for(int j=0;j<sp[0].col;j++)
{
if(k<=sp[0].val&&i==sp[k].row&&j==sp[k].col)
{
printf("%d\t",sp[k].val);
k++;
}
else
printf("0\t");
}
printf("\n");
}
}
int main()
{
struct sparse sp1[10],sp2[10],sp3[10];
printf("for first matrix\n");
readmat(sp1);
printf("for second matrix\n");
readmat(sp2);
displaymat(sp1);
printf("\n\n");
displaymat(sp2);
printf("\n\n");
displaymat(sp3);
return 0;
}`
Updating the original answer:
The reason out of order values are not getting printed is because when the value in triplet form points to an element further down the for loops go past all the other values that could have been printed. For example in your example the 3rd element is at row=1, col=3 however the 2nd element is at row=2,col=2. This will lead to the outer for-loop advancing down to 2nd row. At that point in time the loops will not go back and print 1st row.
One way will be to sort based on the row and col and then print the values.

Matrix Multiplication Issues in C

I'm making a matrix multiplication calculator in C. When I run it, spews out many numbers and results in this:
57736 segmentation fault
Where did I write wrong? Here is the code I wrote:
int Mtx1row, Mtx1col, Mtx2row, Mtx2col, c, d, e;
int first[10][10], second[10][10], mult[10][10];
Get 1st Matrix row and col
printf("First Matrix: # of row and col?\n");
scanf("%d%d", &Mtx1row, &Mtx1col);
Get 2nd Matrix row and col
printf("Second Matrix: # of row and col?\n");
scanf("%d%d", &Mtx2row, &Mtx2col);
Compare 1st Matrix col vs 2nd Matrix row
if (Mtx1col != Mtx2row){
printf("Mtx1col != Mtx2row (x _ x)\n");
return 1;
}
Get elements of first matrix
printf("Enter elements of First Matrix: \n");
for (c = 0; c < Mtx1row; c++)
for (d = 0; d < Mtx1col; d++)
{
printf("\tEnter element %d%d: ", c+1, d+1);
scanf("%d", &first[c][d]);
}
Get elements of second matrix
printf("Enter elements of Second Matrix: \n");
for (c = 0; c < Mtx2row; c++)
for (d = 0; d < Mtx2col; d++)
{
printf("\tEnter element %d%d: ", c+1, d+1);
scanf("%d", &second[c][d]);
}
Multiply Matrix 1 and 2 and store into Matrix Product
for (c=0; c < Mtx2row; c++){
for (d=0; d < Mtx2col; d++){
for (e=0; e < Mtx1col; e++){
mult[c][d] += first[c][d] * second[d][e];
}
}
}
Two matrices could be multiplied if an only if
#columns of the first matrix = #rows of the second matrix.
So you need to check this before creating the 2D arrays themselves.
if(Mtx1col == Mtx2row){
//proceed creating the matrices
int first[Mtx1row][Mtx1col], second[Mtx2row][Mtx2col];
int mult[Mtx1row][Mtx2col]; // The resulting matrix is Mtx1row * Mtx2col
// You have variable length arrays(VLAs) above.
}
else{
// put the f/b code here
}
Note
Under C11, VLAs are an optional feature rather than a mandatory feature,
as they were under C99.
The term variable in variable-length array does not mean that you can
modify the length of the array after you create it. Once created, a
VLA keeps the same size. What the term variable does mean is that you
can use a variable when specifying the array dimensions when first
creating the array.
The above excerpt is from Stephen Prata's C++ Primer Plus 6th edition
At least one of your array variables mult, first, second does not provide enough memory for the accesses happening.
When Mtx2row, Mtx2col and Mtx1col have values between 0 and 10 inclusively, the memory accesses should be fine. So please check the value of these variables. As a first step you can just printf these values, better would be a programmatic check that precludes out of bounds values. Also, please check that the matrices have compatible dimensions for matrix multiplication, i.e. Mtx1col must be equal to Mtx2row.
EDIT:
Now that the shown code includes the scanf statements, I can give the following advice. Always check the return code of scanf to ensure all arguments have been parsed. You can even add an additional %c to ensure there was no extra input. In your case you also have to check if the read array indices are inside the permissible range (here 0-9).

Input in a 2-D array

I was trying to solve a question on 2-D matrix, but unfortunately the matrix input was giving an error. This is the code:
int arr[4][4];
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int i, j;
fflush(stdin);
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &arr[i][j]);
When I run this, it takes extra input.
For example: if r = 2 and c = 2> then it takes 6 input and then hangs. What to do?
If r=2 and c=2, it executes the first 2 scanf and then the 2x2 scanf of your 2D loop.
This makes 2 + 2x2 = 6.
After the last scanf, if your program is finished, it simply closes, that's normal.
I have copied your code and tried executing it and I observed that it is showing the behaviour told by you if we are taking r and c greater than their limits. So use proper limits.
I think the problem with your code is that you've allocated a fixed amount of space for your array but allowed the user to provide an arbitrary number of inputs by making the bounds of your loop the user-provided r and cvariables. Thus if the user provides r=6 and c=6, at some point your loop will attempt to dereference arr[5][5], which is invalid since you've defined int arr[4][4];. If you want to allow the user to create as many rows and columns as they want, you should initialize arr with the user-provided input, like this:
int r,c;
scanf("%d",&r);
scanf("%d",&c);
int arr[r][c];
In your code you have simply run a loop and how much value will be scan depend on the how many loops has executed.
Suppose you take r=1,c=1.
In this condition for every "r" value c will executed single time.
So When your value will be larger than the array size that time it will give you abnormal behavior.
if you will firstly input the value of "c", and "r"after that it will behave normally.
int r, c;
scanf("%d", &r);
scanf("%d", &c);
int arr[r][c];

Resources