This question already has answers here:
Can a const variable be used to declare the size of an array in C?
(5 answers)
Closed 10 months ago.
It is saying that the variable p in the final function int main needs to be a constant but I attempted to change it to a constant and it still didn't run. Any recommendations on ways to fix it?
#define _CRT_SECURE_NO_WARNINGS // Disable warnings (and errors) when using non-secure versions of printf, scanf, strcpy, etc.
#include <stdio.h> // Needed for working with printf and scanf
// defining a function to read input
void input(double* array, int p) {
// looping p times to read p values from user
for (int i = 0; i < p; i++) {
printf("Enter a value for #%d: ", i + 1);
scanf("%lf", &array[i]);
}
}
double processing(double* array, int p) {
// defining a variable to store sum of all values
double sum = 0;
// looping over p values in the array
for (int i = 0; i < p; i++) {
sum += array[i];
}
// return average = sum / size of array
return sum / p;
}
void output(double average) {
// displaying average of all the values
// displaying only one decimal point as given
printf("The average of the values is %.1lf\n", average);
}
int main(void) {
// Constant and Variable Declarations
// defining size and initializing it to 10 as mentioned
int p = 10;
// size of p
double array[p];
input(array, p);
double average = processing(array, p);
output(average);
return 0;
} // end main() '''
Maybe you could call your function so instead of making P a variable:
input(array, 10);
sorry if it doesnt work im new to c as well
Related
I am new to the C language (I started to learn it a week ago). the program was having some random output so i wanted to see what was it storing in the variable. then the printf fixed it somehow.
#include <stdio.h>
int laske(float lista[]);
const int MAX = 3;
int main()
{
float lista[5], yhteispisteet;
int counter = 0;
do
{
printf("Anna %d. pisteet: \n", counter +1);
scanf("%f", &lista[counter++] );
printf("%d",lista[counter]); <-- if you remove this line it dosent work
}
while (counter < MAX);
yhteispisteet = laske(lista);
printf("\nYhteispisteet ovat: %.2f\n", yhteispisteet);
getchar();
return 0;
}
int laske(float lista[])
{
int rivi, tulos;
for (rivi=0; rivi< MAX; rivi++)
tulos = tulos + lista[rivi];
return tulos;
}
Three things to note from your code:
You are adding a float and an int when you do: tulos = tulos + lista[rivi];, without casting the input float to int like this: tulos = tulos + (int)lista[rivi]; Or better yet, just declare tulos as float, and return a float from your laske function, because the return value is again being assigned to a float yhteispisteet
You assign to lista[counter++] with the scanf, and then increment the counter (post-increment) and print the lista[counter](which is printing the incremented indexed value that did not take any assignments yet). It is better to increment counter++ after the printf function.
You did not initialize your variable tulos, and this gives you undefined behavior when your code is running, which is probably what you are seeing when you add and then remove the printf and then rerun
The following code block is only part of a larger one. In the program, I want to find the definite integral of a polynomial that needs to be inputted by the user.
I'm new to C and so I'm having a hard time trying to learn the syntax with regards to pointers. I find them very confusing.
So if you'll look at the code block below, I want to print the elements contained in the array coefficients just so I can see if the elements inputted are being stored in the array but to no avail. The program just terminates after the inputCoeffs() function.
#include <stdio.h>
#include <stdlib.h>
void inputDegree(int *deg) {
printf("Enter the degree of the polynomial: \n");
scanf("%d", *°);
}
void inputCoeffs(int deg, double *coeffs) {
printf("Enter the coefficients of the polynomial (A, B, C,...): \n");
for(int i = 0; i <= deg; i++) {
scanf("%lf", &coeffs[i]);
}
}
int main() {
int i;
int degree;
double lowerLimit;
double upperLimit;
double integral;
double *coefficients = NULL;
double *integralCoefficients = NULL;
inputDegree(°ree);
coefficients = (double*)malloc((degree + 1) * sizeof(double));
integralCoefficients = (double*)malloc((degree + 1) * sizeof(double));
inputCoeffs(degree, &coefficients);
for(i = 0; i <= degree; i++) {
printf("\t%lf\n", coefficients[i]);
}
return 0;
}
In this call
scanf("%d", *°);
it is enough to write
scanf("%d", deg);
It is unclear why you are allocating memory one element greater than the value of degree.
coefficients = (double*)malloc((degree + 1) * sizeof(double));
In this case the allocated array has degree + 1 elements.
The type of the second argument in this call
inputCoeffs(degree, &coefficients);
is invalid. There shall be
inputCoeffs(degree, coefficients);
The & operator is used to get a pointer to an existing variable, while * is used to dereference a pointer. Therefore
inputCoeffs(degree, &coefficients);
Makes no sense, because coefficients is already a pointer. inputCoeffs
accepts a pointer so you can just write
inputCoeffs(degree, coefficients);
Since the & and * operators basically do the opposite, this line
scanf("%d", *°);
is not an error, but could also just be written as
scanf("%d", deg);
Also, you should call free when ever you use malloc, so add to the end of the code:
free(coefficients);
free(integralCoefficients);
I am new to the C.Sc course and we are taught C program.
I was trying some of the basic stuff. Currently I am learning User-Defined-Function.
The following code is the one I was trying with. I know it is pretty simple but I am not able to understand why it is producing such weird output.
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
}
int add(int a) //function definition
{
int result;
for(int i = 0; i < a; i++)
{
result = result + i;
return result;
}
}
The output for 1 is 32743
The output for 2 is 32594
The output for 3 is 32704
The weird thing is output change each time for the same number.
It's just weird considering my experience in C.Sc. till date. Kindly explain what the program is doing.
This is the right place to post problems like this. Right?
You forget to initialize result.
int result = 0;
Explanation : If you do not initialize the variable, it will have a "random" number, and then you are going to get "random" output
Also :
You also forgot to return something if a = 0, or a negatif number !
And your main NEED to return a int.
Also, there is no point to do a loop since you return inside of it, you always going to return 0 in the loop.
Here is a correction of your code :
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
return 1;
}
int add(int a) //function definition
{
int result = 0;
for(int i = 0; i < a; i++)
{
result = result + i;
}
return result;
}
Exemple with 10 as input : https://ideone.com/6BjM6y
You need to initialize result,
int result = 0;
In your code, result is not initialized so at the
result = result + i;
line, you use whatever value result has and it's not possible to determine which value is that because it's a garbage value.
In c, variables are not automatically initialized for performance reason, with a few exceptions, the most notable are
Local variables with static storage class.
Global variables.
when you leave a variable uninitialized, then trying to read it's value is considered undefined behavior.
In response to your comment
The problem is that you return after adding 0 to result which is 0, so move the return result; outside of the for loop and it should work.
You need to initialize the variable result. Since it is bot initialized, the compiler initializes it with a default value, which could be a "funky" mumber. To fix this, initialize result in your Add() function to:
int result = 0;
Another thing: your return statement is inside the for-loop. This means that the for-loop will terminate at the end of the first loop since there is a return statement that will terminate the function. To fix it, change your function to:
int result;
for(int i = 0; i < a; i++)
{
result += i; // shorthand way of writing result = result + i. Same end result
}
return result; // should be outside the loop
I've gone over the code and re-written it several times already and each time I get 0s when printing the array and the mean. I'm using codeblocks as the ide.
Below is statlib.c
// Calculates the mean of the array
double calculateMean(int totnum, double data[ ])
{
double sum = 0.0;
double average = 0.0;
int i;
// adds elements in the array one by one
for(i = 0; i < totnum; i++ )
sum += data[i];
average = (sum/totnum);
return average;
}// end function calculateMean
Below is the other file
#include "statlib.c"
#include <stdio.h>
int main (void){
int i; // counter used in printing unsorted array
double mean = 0.0;
double data[10] = {30.0,90.0,100.0,84.0,72.0,40.0,34.0,91.0,80.0,62.0}; // test data given in assignment
int totnum = 10; // total numbers in array
//Print the unsorted array
printf("The unsorted array is: {");
for ( i = 0; i < totnum; i++){
printf(" %lf",data[i]);
printf(",");
}
printf("}\n");
//Get and display the mean of the array
mean = calculateMean(totnum,data);
printf("The mean is: %lf\n",mean);
return 0;
}
You are trying to print mean with a %lf format specifier. That format specifier isn't valid, so probably something goes wrong there.
The correct format specifier for double would be %f, and the l length modifier is only allowed for integer formatting. (For floating point there is L, making %Lf the correct format specifier for long double).
Using the same machine and IDE as reffered in my other question (third paragraph at Problems in code or my IDE/comp is bugged?)
I try to run this code:
#include <stdio.h>
#define n 3
int main()
{
int i;
float values[n],sumval,svmean,tmp;
for(i=0;i<n;++i)
{
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
return(0);
}
The above code is supposed to run this formula
That means that it has to add some values and divide the result by their total number.
As you see above I made an array with random n positions and I ask the user to fill in a value for each position then add them all up and divide them.
The problem is that it doesnt work. It outputs only the result 7 no matter what the iput is.
BUT if I include stdlib.h to the code it works fine.
so
Question A: why the code does not work properly using only the
stdio.h library? which element of the code does require the stdlib.h
library?
As you see the array values[n] seems to have an random n number of cells but actually I have already set this numer to be equal to 3 (using #define)
Question B: Is there a way to run a code with the same porpuse but letting the user to define the size of the array values[n] or in other words let the user input an integer that sets the value of n in values[n]?
First of all, you forgot to initialize sumval. You want it to be 0 at the beginning.
If you want the size of the array to be decided at runtime, you have to allocate it dynamically using malloc, for example like this:
int n;
float *values,sumval=0,svmean,tmp;
scanf("%d", &n);
values = (float *) malloc (n * sizeof(float));
Later, you should release the memory allocated by calling free:
free(values);
Initialize sumVal to o. Because for first iteration it adds garbage+values[i] into sumValue.
#include <stdio.h>
#define n 3
int main()
{
int i;
float values[n],sumval=0,svmean,tmp;
for(i=0;i<n;++i){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
sumean = sumval/n;
printf("%f \n",svmean);
return(0);
}
The problem is that you do not initialize sumval. You should set it to 0.0 before you for loop.
The change occurring when including/not-including stdio.h is probably due to some initialization functions using the stack, and changing the values in memory, before you enter your function, and it happen that this memory is used for your sumval variable.
But you should NOT rely on this.
Question A answer
In the code you posted there is no need for stdlib.h. This library is needed if you use a function for allocating memory dynamically, such as malloc().
Question B answer:
This is a way to do what you want:
#include <stdio.h>
int main()
{
int i, choice;
float *values,sumval,svmean,tmp;
printf("Please enter the size of the array: ");
scanf("%d", &choice);
values = (float*) malloc(choice*sizeof(float));
for(i=0;i<n;i++){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
free(values);
return 0;
}
Also, I modified the incrementation of i in the for statement to increase after running the loop.
Try this..
#include <stdio.h>
int main()
{
int i = 0;
int n = 0;
float sumval = 0;
float svmean = 0;
float tmp = 0;
printf("Enter count : ");
scanf("%d", &n);
for (i = 0; i < n; ++i) {
scanf("%f", &tmp);
sumval = sumval + tmp;
}
svmean = sumval/n;
printf("%f \n",svmean);
return(0);
}
In your code, values[] array is not necessary to calculate output. Are you storing the values for any reason??..
You can allocate an array with variable size in the heap of the program like that:
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
//Get the size of the array from input parameter
int n = atoi(argv[1]);
float sumval,svmean,tmp;
//Allocate the array of values
float *values = malloc(sizeof(float)*n);
// Initialize sumval
for(sumval=0,i=0;i<n;++i){
scanf("%f",&tmp);
values[i]=tmp;
sumval = sumval + values[i];
}
svmean = sumval/n;
printf("%f \n",svmean);
//Free it
free( values );
return(0);
}
You also need to initialize sumval to 0. The parameter of the size of the array is passed when launching the program (if you use an IDE you should check how it does that)