Gauss Jordan Method in Basic C Multi - c

I am have a multi-dimensional array that needs to be resolved, to solve for the unknown values (x1,x2,x3,..). In this multi-dimensional array, my array size in the i and j coordinate are different; B[n][n+1]. I know this Basic C, Gauss Jordan Method to solve for the unknown, is incorrect and would like someone to point in how to modify it..
This code is accurate for an Array with the same n values only; eg. A[n][n].
//Computation to solve
for(j=0; j<=n; j++)
{
for(i=0; i<=n; i++)
{
if(i!=j)
{
c=B[i][j]/B[j][j];
for(k=0;k<=n+1;k++)
{
B[i][k] = B[i][k] - c*B[j][k];
}
}
}
}
//Print Solution
printf("\nThe solution is:\n");
for(i=0; i<=n; i++)
{
x[i]=B[i][n+1]/B[i][i];
printf("\n x%d=%.3f\n",i,x[i]);
}
An example would be if my n=2. The array that i would want to solve is B[2][3].
0 -20 0 -1
0 30 -10 0
0 -10 10 1
The output of this code is
x1= -inf
x2=0.050
x3=0.000
The correct output should be
x1=0.00
x2=0.05
x3=0.15

This code is accurate for an Array with the same n values only; eg.
A[n][n].
No, the code already accounts for column n+1 (which holds the right-hand constant terms) in the loop
for(k=0;k<=n+1;k++)
{
B[i][k] = B[i][k] - c*B[j][k];
}
(since k runs up to n+1). So, it is correct in this regard.
An example would be if my n=2. The array that i would want to solve is
B[2][3].
C arrays are declared by specifying the number of elements in the array, not the highest index, so you want B[3][4].
The main fault of the shown code is its lack of the row swapping operation, which may be necessary if B[j][j] is zero, and the related test. We can implement that by inserting
if (!B[j][j])
{
for (i=j+1; i<=n; i++)
if (B[i][j]) { swap(B[j], B[i]); break; }
if (!B[j][j]) continue; // leave all-zero column as is
}
at the beginning of the for(j=0; j<=n; j++) loop body (implementing swap() left to the reader).
The correct output should be
x1=0.00
Whether this is correct is debatable, but if you want a variable where every number is a solution to take the value zero, you may insert
if (B[i][i] == 0 && B[i][n+1] == 0) x[i] = 0;
before the printf("\n x%d=%.3f\n",i,x[i]).

Related

Enter unknown number of array values in C/C++ has strange behaviour

I need to populate an array of integers with an unknown number of elements. I am using a while loop to input values and exit the loop as a non integer value is entered. Outside the loop an integer j is initialized at 0 and used to address array elements inside the loop. At each round of the loop I check the value of j before and after the input value is assigned to array element v[j], then j is incremented.
Depending on the size chosen for the array in the declaration, (in the example below v[8]), index j is unexpectedly affected by the assignment itself: in the example below when j equals 11 before the assignment it becomes 2 after the assignment, thereafter messing it all up. As a result the code fails to assign the correct input values to the array.
I am surely lacking some deeper knowledge about C/C++ array management... anyone can help to to fill the gap explaining the apparently strange behaviour of my code?
#include <stdio.h>
int main()
{
int j = 0, m, v[8];
printf("Enter an integer: to finish enter x\n");
while (scanf("%d", &m))
{
printf("j before assignment:%d - ", j);
v[j] = m;
printf("j after assignment:%d - ", j);
printf("v[j] after assignment:%d\n", v[j]);
j++;
}
return 0;
}
You write beyond the array boundaries of v. To avoid this, check j in a for loop, e.g. replace while (...) with
for (j = 0; j < 8 && scanf("%d", &m) == 1; ++j) {
// ...
}
This way, the loop stops after the end of the array (v[7]) is reached.
To comment the "strange" behaviour, read about stack and stack layout, e.g. Does stack grow upward or downward?
As always, check the C tag wiki and the books list The Definitive C Book Guide and List

Specific for-loop for a simple sort algorithm

this is a simple code for sorting a table from max to min. I am confused because my professor used for(i=0; i<10-1; i++) and I saw that it works fine with for(i=0; i<10; i++). Can please someone tell me the difference?
Thanks for your time, appreciate your help.
int a[10];
int i, j, t;
for(i=0; i<10; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<10-1; i++)
{
for(j=i+1; j<10; j++)
{
if (a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0; i<10; i++)
{
printf("%d\n", a[i]);
}
Your professor is correct, although your way does work too; it's just clumsier:
Given that the starting value of j is i + 1, in order to avoid a out of bounds access to the array a (the behaviour of which is undefined), you need to constrain i to be less than 9 and i + 1 to be less than 10. Essentially your professor constrains the former, but you constrain the latter.
The bubble sort works this way as sortedness is established once the outer loop has processed the penultimate element.
Converting my comment:
Usually, these kind of algorithms do not stop at the last one, but an element before. In fact, at that point, the nth-1 element is already sorted with respect of the nth one. So, both works, but the "-1" is more efficient because you skip a useless iteration.
In case of for(i=0; i<10; i++) you get one additional iteration of the external loop, in wich i is equal 9. But then in the internal loop j is equal 10 at once, condition j < 10 isn't met, and the internal loop terminates without executing its body.

Why is this code outOfBound?

Here is a problem I met the other day in a interview, would someone tell me the "truth" behind this "simple" code?
#include<stdio.h>
int main()
{
int a[]={1,2,3};
for(int i=0; i<=3; i++){
a[i]=0;
printf("%d\n", i);
}
return 0;
}
Everything will be right if <= is replaced by < as it is causing array out of bound index error and will print value
0
1
2
3
although the value of the array content will be 0 every time
The loop variable i takes on values 0, 1, 2, and 3. Unfortunately, 3 is an out-of-bounds index for array a, which only has length 3 (legal indices 0, 1, and 2). To avoid an out-of-bounds array access, the loop control should be
for(int i=0; i<3; i++){
Note the use of < instead of <=. As an interview question, the goal was to test whether you noticed this very common kind of off-by-one error.

increment array in a formula

My program is meant to calculate the linear regression coefficients given the array "input" using least squares method. My issue is when attempting to calculate the slope of data. As you can see the array "input" is a 2 row array. I was able to separate the two rows as input[i] and input[j]. But in order to find the slope I need to use these two rows separately and increment them in the equation to solve for v. How do I use these two arrays to get the value of v?
Note: Using the input shown in the image below, v and be should be 2.795 and -3.891 respectively.
My assignment:
http://i1306.photobucket.com/albums/s576/sammyr2011/assignment2question4_zps08a5464b.jpg
My code so far:
/*
* Program: linreg.c
* A program that calculates the linear regression coefficients
* v and b using the least squares method.
*/
#include <stdio.h>
#include "forStatLib.h"
double input[][10] ={{0, 5, 10, 15, 20, 25, 30 ,35, 40, 45}, {0, 13, 22, 37, 54, 62, 64, 100, 112, 126}};
// Use the sum += when inputting array into equation
int main() {
int first, second, i, j, k;
double v, b, t, y;
//grab 1st row of the array
for(i=0; input[0][i] ; i++) {
input[i];
}
//grab 2nd row of the array
for(i=0; input[1][i]; i++) {
input[j];
}
/*calculate the average of both rows, first row is t and second is y.
Then assign the averages of each as t_a and y_a. */
double t_a, y_a;
t_a = mean(10, input[i]);
y_a = mean(10, input[j]);
//calculate v (slope), Maybe use two loops with one nested?
// i need to increment
v = ( - t_a)( - y_a) / ( )
}
make these changes,
t_a = mean(10, input[0]);
y_a = mean(10, input[1]);
//calculate v (slope), Maybe use two loops with one nested?
// i need to increment
v1=0;
v2=0;
for(i=0; i< 10; i++)
{
v1+ = ( input[0][i] - t_a)*( input[1][i] - y_a);
}
for(i=0; i< 10; i++)
{
v2=v2+( input[0][i] - t_a)*( input[0][i] - t_a);
}
v=v1/v2; //use float or double data type
input[][] is a 2D array so to access the elements use input[i][j] form.
and i dont know why you used,
for(i=0; input[0][i] ; i++) {
input[i];
}
//grab 2nd row of the array
for(i=0; input[1][i]; i++) {
input[j]; // j not initialized
}
if to print the values use printf()
for(i=0; i<10 ; i++) {
printf("%d",input[0][i]);
}
//grab 2nd row of the array
for(i=0; i<10; i++) {
printf("%d",input[1][i]);
}
I wont give you the answer to your question or to your assignment, but something I think you will need a lot more at the moment: it seems you haven't really got a grasp on array manipulation. I'll try explain what your code is doing, so then you can modify / write / debug this and other code.
//grab 1st row of the array
for(i=0; input[0][i] ; i++) {
input[i];
}
What you have done till here is to increment the values of of i step by step till input[0][i]=0. For loops are written as follows for(do_this_once_in_the_begining;Keep_looping_if_this_is_true;do_this_once_per_loop) In C false=0 and true=nonzero.
str="my string"; for(i=0; str[i] ; i++) will work because the last element of any string is the number 0 (not the ascii character'0'). This wont work for an array f integers.
In the body of the loop you just read each element of the array and did nothing to it. If you wanted to you might have put a printf("%f",input[0][j]) so you view the elements. However, this does not do anything else.
And you don't need to "grab" anything. Your array was all setup when you declared it.. nothing more needed to be done.
The last part:
Your formula has two separate sigmas that are calculated separately, so you will need to use two for loops (you can do it in one, try figure it out, it will go a long way in solving other problems) BUT, you are not required to take a sigma of a sigma, so you wont need to nest them.
For example just calculate the v_denominator like this:
double v_denom=0;
for(i=0;i<10;i++){
v_denom+=( input[0][i] - t_a)*( input[0][i] - t_a);
}
try this
for(i=0 ; i < 10 ; i++)
v +=(input[0][i]-t_a)*(input[1][i]-t_y);//numerator
similarly calculate denominator and divide

Bowling score calculator in C

This is a homework problem. I'm currently in the process of writing a program that calculates one's bowling score. My logic is to use multidimensional arrays with 9 frames as the rows and 2 throws as the columns. I will account for the 10th frame at the very end due to its unique nature of having possibly up to three rolls. The addition of strikes and spares also complicate the question, so I felt like I needed to use arrays to keep track of past and future rolls. I know it's not required but I couldn't think of another way.
Here is my code so far:
for (i=0; i<9; i++)
{
for (j=0; j<2; j++)
{
scanf("%d", &score[i][j]);
tempTotal += score[i][j];
}
}
printf("temporary: %d\n", tempTotal);
//strike
for (i=0; i<9; i++)
{
for (j=0; j<2; j++)
{
if(score[i][0] == 10 && score[i][1] == 0)
{
total = tempTotal + score[i+1][0] + score[i+1][1];
}
//spare
else if ((score[i][0] + score[i][1]) == 10)
{
total = tempTotal + score[i+1][0];
}
else
{
total = tempTotal;
}
}
}
printf("result: %d\n", total);
Here is an update of my progress. As per the comments, I used scanf to fill up my multidimensional array first. And then I looked through the array to account for the cases of strikes and spares. The code works until there are consecutive strikes and/or spares. How do I account for the accumulation of consecutive spares and/or strikes? Am I supposed to add additional conditional statements within my strike and spare conditions to account for if score[i+1][0] is another strike in which case I have to account for that additional 10 points plus the next three throws as well? How can I make such a conditional statement that comprehensively searches through the entire array like that? Any ideas would be appreciated. Thank you.

Resources