C Program forLeast Square Regression Line and Errors - c

I wanted to create a program to calculate the regression line of some given data, along with the errors, so I can use in my university assignments. This is the following program:
#include <stdio.h>
#include <math.h>
int main(void)
{
int i,n,N;
double x[n],y[n],a=0.0,b=0.0,c=0.0,d=0.0,D,P=0.0,p,Sx,A,B,dA,dB;
printf("Give the number of data you want to input for x : ");
scanf("\n%d", &N);
printf("\nGive the values of x : ");
for (i=1; i<=N; i++);
{
printf("\n Enter x[%d] = ", i);
scanf("%lf", &x[i]);
a+=x[i];
b+=pow(x[i],2);
}
printf("\nGive the values of y : ");
for (i=1; i<=N; i++);
{
printf("\n Enter y[%d] = ", i);
scanf("%lf", &y[i]);
c+=y[i];
}
D=N*b-pow(a,2);
A=(b*c-a*d)/D;
B=(N*d-a*c)/D;
for (i=1; i<=N; i++);
{
d+=x[i]*y[i];
p=y[i]-A-B*x[i];
P+=pow(p,2);
}
Sx=sqrt(P/N-2);
dA=Sx*sqrt(b/D);
dB=Sx*sqrt(N/D);
printf("\n x \t \t \t y");
for (i=1; i<=N; i++);
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
printf("\nA = %lf\t B = %lf", A,B);
printf("\nThe errors of A & B are dA = %lf and dB = %lf", dA,dB);
printf("\nThe equation of the regression line is y=%lfx+(%lf)", B,A);
return 0;
}
I have two problems.
Despite giving a value to N, the program runs so that I can only give one value for x and one value for y. Why and where is the mistake?
When printing the "Enter x[%d]", it displays x[11] and at the end when printing "x[%d] = %lf\t%lf = y[%d]", it displays x[0]. Again why and where is the mistake?
Thank you for your help!

You are trying to create a dynamic array in C.
To do that, you need to use dynamic memory allocation with malloc and free. So, your code should look something like this:
int N;
double *x;
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
x = malloc(sizeof(double) * N);
Then, at the end of your program you need to free the memory:
free(x);
If you don't want to deal with manual memory management (or can't for some reason), you can use a static maximum array size like this:
#define MAX_N_X 100
int main(void) {
int N;
double x[MAX_N_X];
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
if (N > MAX_N_X) {
printf("Can't handle that many inputs! Maximum %d\n", MAX_N_X);
return 0;
}
}
You simply missed two parameters to printf.
Yo wrote:
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
But it should be:
printf("\nx[%d] = %lf\t%lf = y[%d]", i, x[i], y[i], i);

I found the main problem with this program a few days after posting this and the fix would be removing the ; from the for commands, along with some other minor changes. I thought I might add this comment to let you know and now it is working like a charm. The simplest of mistakes fools even the trained eyes. After I found this, I was shocked that no one picked up on this mistake.

Related

Why is 1st for loop isn't getting executed in Code blocks?

This is a program to find norm of a matrix. I am using Code Blocks to write codes. The 1st for loop in this code which is used to fill the matrix doesn't get executed in Code Blocks but gets executed in a online c compiler. Why is this happening?
///find the norm of a matrix
#include<stdio.h>
#include<math.h>
void main()
{
short int r,c;
register short int i,j;
//fill matrix
printf("\nENTER MATRIX DIMENSION");
printf("\nROWS: ");
scanf(" %d",&r);
printf("COLUMNS: ");
scanf(" %d",&c);
printf("\ncheck1");
--r; --c;
printf("\ncheck2");
float mat[r][c],sum,norm;
printf("\ncheck3");
//1st for loop:fill array
for(i=0 ;i<= r ;i++)
{
for(j=0 ;j<= c ;j++)
{
printf(" \nELEMENT %d x %d: ",i,j);
scanf(" %f",&mat[i][j]);
}
}
printf("\ncheck4");
//finding norm
sum = 0;
for(i=0;i<=r;i++)
{
for(j=0;j<=c;j++)
{
sum = sum + pow(mat[i][j],2);
}
}
norm = pow(sum,0.5);
printf("\n\nNORM: %f",norm);
}
The code is correct but the for loop is not executing because the condition:
for(i=0;i<=r;i++)
i<=r is getting false.
Why?
Because garbage value is being stored in your variable r and c.
You are using format specifier %d which is for int.
The Format specifier for short is %hd.
Just use %hd and everything will work fine.

Array: issues declaring

I've been trying to convert my python to C code and it's my first time using C.
Basically I want it to ask how many grades I will input and then put them in an array. The problem is that the amount keeps putting in the array. I thought that I could declare the size of the array after asking how many grades I was inputting but I think that's the problem. I am not sure how else to do it. I have a lot of printfs I was using for debugging.
Any Suggestions?
double enter_quiz_grades()
{
int quiz_amount,loop,i;
printf("Enter number of quiz grades to enter:");
scanf(" %d \n", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp=0;
double grades[quiz_amount];
for (loop = 0; loop<quiz_amount;loop++)
{
printf("loop is %d", loop);
i = loop+1;
printf("Enter grade for quiz %d: ",i);
scanf("%lf\n", &temp);
grades[loop] = temp;
printf("%lf",grades[loop]);
}
return 0.0;
}
The problem is you are using '\n' inside scanf. Also you can get rid of additional variables.
Here is the modified code:
double enter_quiz_grades() {
int quiz_amount, i;
printf("Enter number of quiz grades to enter:");
scanf("%d", &quiz_amount);
printf("You typed %d students\n",quiz_amount);
double temp = 0;
double grades[quiz_amount];
for (i = 0; i < quiz_amount; i++)
{
printf("loop is %d\n", i);
printf("Enter grade for quiz %d: ", i + 1);
scanf("%lf", &grades[i]);
printf("%lf\n",grades[i]);
}
return 0.0;
}
Just a small detail, not strictly related to the original question:
double grades[quiz_amount];
This creates an array, sized at runtime, from a variable. If this variable is read from somewhere, this can lead to a malicious user giving it a very high (or ngative!) value, and you are in big problems. The linux kernel is removing them from the source for this exact reason (as this syntax creates the array in the stack - attacker can modify the return address). Make this a dynamic array allocated on the heap (malloc()).
https://www.phoronix.com/scan.php?page=news_item&px=Linux-Kills-The-VLA

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

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

C program with two dimensional arrays?

in a two dimensional array there are kept the working hours for N workers and M projects,the names of the workers are kept in an array with the name Worker and the name of the projects in an array with the name "Project".Write a program which reads the data and displays the worker with more working hours.So I tried this,but everytime I ran it,it seems to be a logical error,because it says :Give the number of the project,and If I type "2" this is also the number of the workers according to my program,and then it asks for the hours for each worker..
#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, n, worker[100][10], hours[30][100];
printf("The number of the project: ");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("Give the worker %d: ", i+1);
scanf("%s", &worker[i]);
}
for (i=0; i<n; i++)
{
printf("\n The worker %s\n", worker[i]);
for (j=0; j<30; j++)
{
printf("The number of the hours for the day %d: ", j+1);
scanf("%d", &hours[i][j]);
}
}
for (i=0; i<n; i++)
{
for (j=0; j<30; j++)
if (hours[i][j]==0)
break;
if (j==30)
printf("%s\n", worker[i]);
}
getch();
return 0;
}
You seem to be taking the input incorrectly.
scanf("%s", &worker[i]);
worker is a 2D array of type int. So, you need to have another index while taking input. Also the format specifier for int is %d. Any decent compiler should have given you warnings during compilation.
Seems to me that you first must ask how many workers (N) and how many projects (M) with something like:
int ii, m, n;
char **worker;
char **project;
printf("How many workers? ");
scanf("%d", &n);
printf("How many projects? ");
scanf("%d", &m);
Then ask for the names of the workers:
// Allocate space for n worker string pointers
worker = (char **)malloc(n * sizeof(char *));
for (ii = 0; ii < n; ++ii)
{
char bufname[1024]; // danger here if input too long
printf("Name of worker[%d]? ", ii + 1);
scanf("%s", bufname);
worker[ii] = strdup(bufname);
}
Then ask for the names of the projects, similarly. Then get the hours, then calculate the max, then free up the dynamically allocated worker & project strings (and the two array of pointers).

Resources