Array: issues declaring - c

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

Related

C program does not recognize my input for 'max'

Hi I keep trying to figuure this out but my input keeps getting ignored, thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main(){
float a, b, a0, b0,i;
char ans;
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf(" %c", &ans);
while(ans == 'max'){
printf("maximum selected");
}
printf("minimum selected");
return 0;
}
First of all, you're comparing a single char to a whole string, so you need to modify your ans variable declaration to make it a string, like:
char ans[4]
Keep in mind, this will have a maximum size of 3. If you need to store a bigger string, you'll need to modify this.
Then, after doing this, using a while to do that comparison isn't correct. It's better to implement an if-else. And, inside that, the comparison you're doing is wrong. You need to compare strings, not chars, so you need to use strcmp() function, like:
strcmp(ans,"max") == 0
If this function returns a 0, it means both strings are equal.
Another thing to comment is that you will need to modify your scanf to scan a string, not a char, the new one will be scanf("%3s", &ans);.
And let me tell you one more thing. The for you're using has no sense. You're using a for with parameters i = 1; i <= 1; i++. That means i will start the buckle fulfilling the conditions to break it, so it will only be executed once. In other words, the code inside that for will be executed just once, no matter if it's inside or outside the for.
Anyway, and to sum up, here's your new code:
int main(){
float a, b, a0, b0,i;
char ans[4];
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf("%3s", &ans);
if(strcmp(ans,"max") == 0)
printf("maximum selected");
else
printf("minimum selected");
return 0;
}

Print all inputted number by the user in C

I am trying to print all inputted number by the user using the code below but instead of printing all inputted numbers it only print the last number I inputted.
#include<stdio.h>
int display(int n, int a, int b)
{
printf("\n\nOrdered pairs are: ");
for(int j=0;j<n;j++)
{
printf("(%d,%d) ",a,b);
}
return 0;
}
int main()
{
int num,i,j,x,y;
printf("Total number of points: ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n\nPoint #%d: \n",i+1);
printf("x=");
scanf("%d",&x);
printf("y=");
scanf("%d",&y);
printf("Point #%d: (%d,%d)",i+1,x,y);
}
display(i,x,y);
return 0;
}
You don't have memory for storing more than 2 numbers (x and y) which are over-written during each iteration of the loop.
Perhaps you meant to use arrays, or dynamically allocated memory. This:
int x[100], y[100];
is one way, then you can store up to 100 numbers in each of the two arrays. Use array indexing when accessing.
Actually you are changing the value stored in x and y again and again and so, the previous values get destroyed and only the last value is stored. So you can you arrays (which are more easier to use) or you can even use structure (I would prefer to use arrays).

Having problems with 2D char arrays

So I've got an assignment where my program asks the brand (10 letters), model (10 letters), age (1986 - 2019) and cost (positive real number) of 10 cars and then wants the program to check which car is the oldest and to print out it's brand and model. I don't have a problem with the first part but with the second part.
The code is:
//First part
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C 10
#define M 11
int main(void)
{
char brand[C][M];
char model[C][M];
int year[C];
float cost[C];
int i, len1, len2, min;
for(i=0; i<C; i++){
printf("Car %d\n", i+1);
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
do{
printf("Model: ");
scanf("%s", model[i]);
len2 = strlen(model[i]);
} while(len2<0 || len2>10);
do{
printf("Year: ");
scanf("%d", &year[i]);
} while(year[i]<1986 || year[i]>2019);
do{
printf("Cost: ");
scanf("%d", &cost[i]);
} while(cost[i]<=0);
}
//Second part
year[0] = min;
for(i=0; i<10; i++)
if(year[i] < min){
min = year[i];
printf("\nThe oldest car is %s %s\n", brand[i], model[i]);
}
For some reason it either prints out gibberish in the place of brand[i] or if I lose the columns of the if statement prints out all the car brands and their models, where I only want the oldest one.
Aside from scanf not being recommended there are some problems with this code, first when you read the brand and model you do:
do{
printf("Brand: ");
scanf("%s", brand[i]);
len1 = strlen(brand[i]);
} while(len1<0 || len1>10);
The problem here is that you first write the string to brand[i] and then check if it's too long, but you have already written it into the array so if the string is longer than your space you already have a buffer overflow. Limit the size you can read with scanf using scanf("%10s, brand[i]) or better yet use fgets(brand[i], sizeof(brand[i]), stdin).
Next in the second part you use min without initializing it, and you overwrite the content of year[0] with it. You probably wanted something like:
min = 2020; // or a number that will be bigger than all your cars anyway
int older = 0;
i = 0;
for(i=0; i<C; i++){ // Use C here, you have it might as well use it instead of magic numbers
if(year[i] < min){
older = i;
min = year[i];
}
}
printf("\nThe oldest car is %s %s\n", brand[older], model[older]);
but bare in mind that this solution will print multiple cars if they are the oldest ones and have the same year

C Program forLeast Square Regression Line and Errors

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.

C programming return value odd

I tried to search this everywhere, but it's kind of difficult to word, it's most likely a simple fix. Basically when I go through my program that is supposed to compute the average rainfall for a year, it comes out with a very large number, however, I thought it may have been just that I was doing the arithmetic wrong or had a syntax error of some sort, but that was not the case, when I checked the value that the function returned it was the proper value.
#include <stdio.h>
#include <string.h>
void getData(float *, float *);
int main()
{
char state[2], city[81];
float rainFall[12], outputAverage, *pAverage;
printf("Name Here\n");
printf("Please enter the state using a two letter abreviation: ");
gets(state);
printf("Please enter the city : ");
gets(city);
pAverage = &outputAverage;
(getData(rainFall, pAverage));
printf("%.2f", outputAverage);
return (0);
}
void getData(float *rainFall, float *pAverage)
{
int i;
float total;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
you need to initialize total
float total = 0.0;
Initialize the total to 0
Why you make it complicated? Why not just
return total / 12 ?
and called it like
outputAverage = getData(rainfall)
This is a classic problem in C programming. You are mixing strings and numbers on the input. You are better off reading the input into a string and then, using sscanf to parse it properly.
You have uninitialized variable total which is taking garbage value, thus you see a very large answer.
changed your main.. have a look and let me know if you have understood what changes i have made?
#include <stdio.h>
#include <string.h>
void getData(float *);
int main(int argc, char*argv[])
{
char state[3]={0}, city[81]={0};
float outputAverage;
printf("Name Here\nPlease enter the state using a two letter abreviation: ");
scanf("%s",state);
printf("Please enter the city : ");
scanf("%s",city);
getData(&outputAverage);
printf("The Average Rainfall recorded for the year is %.2f\n", outputAverage);
return 0;
}
void getData(float *pAverage)
{
int i;
float rainFall[12]={0}, total=0;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
However instead of using gets you should use fgets but i forgot how to counter the issue of using simultaneous fgets to read input from the standard input stream.
Also initialize the total variable as you are adding in the loop new values to existing value in that variable which would not necessarily add to zero as the premier element. so it could be any garbage value + loop values.
I understand you are practicing pointer concept so you passed the address of the array of floats to your second function but if the rainfall function is not useful in main, Better to restrict the same where it would be useful

Resources