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
Related
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
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 have the following code in C :
#include <stdio.h>
// Global variables :
int i;
int x[10];
int Nmax;
int sum;
// Functions used :
void Summation();
int Average(float avg); // This function will return avg
int main()
{
float avg;
printf("Mention how many numbers to be added\n");
scanf("%d",&Nmax);
printf("Enter %d numbers\n",Nmax);
for (i=0; i<Nmax; i++){
scanf("%d",&x[i]);
}
Summation();
Average(avg);
printf("%d %d %f\n",Nmax,sum,avg);
printf("Average = %.2f\n",avg);
return 0;
}
// Summation :
void Summation()
{
sum=0;
for (i=0; i<Nmax; i++) {
sum=sum+x[i];
}
printf("Sum of them = %d\n",sum);
}
// Average
int Average(float avg)
{
avg=(float)sum/(float)Nmax;
return avg;
}
Somehow the function Average is not returning the expected average value.
Instead it's showing a garbage value.
A typical input/output :
Mention how many numbers to be added
4
Enter 4 numbers
1 2 3 4
Sum of them = 10
4 10 1637156136366093893632.000000
Average = 1637156136366093893632.00
What's going wrong here? Hope I don't require a pointer here or do I?
For the average function you are passing the argument as pass by value. Once you call the function your are not assigning the return value back to the avg variable inside the main function. So what you are printing is the garbage value inside the avg variable declared in main function. Change your code to
avg = Average(avg);
Also this is a very bad way of writing c programs. Please dont you use global variables if you dont need them.
You are mixing int and float and that can cause problems.
You are never initializing avg in main(), use parameters instead of global variables to avoid the confusion. You pass avg's value to Average() it has absolutely no use in this case.
In c parameters to functions are always passed by value so the value of avg is not being modified in Average(), you may think it is because you seem confused about how you can modify global variables everywhere. The truth is global variables are mean, of course they have their uses for example, a global state in a library could be stored in a global variable1 but generally they are not needed.
Try like this
#include <stdio.h>
// Functions used :
float Summation(float *data, int size);
float Average(float *data, int size); // This function will return avg
int
main(void)
{
int size;
printf("Mention how many numbers to be added\n");
if (scanf("%d", &size) == 1)
{
float data[size];
float sum;
float average;
int i;
printf("Enter %d numbers\n", size);
for (i = 0 ; ((i < size) && (scanf("%f", &data[i]) == 1)) ; i++)
;
size = i;
sum = Summation(data, size);
average = Average(data, size);
printf("%d %f %f\n", size, sum, average);
printf("Average = %.2f\n", average);
}
return 0;
}
// Summation :
float
Summation(float *data, int size)
{
float sum;
sum = 0;
for (int i = 0 ; i < size ; i++)
sum = sum + data[i];
return sum;
}
// Average
float
Average(float *data, int size)
{
return Summation(data, size) / (float) size;
}
Note that you "don't really need an Average() function.", although it could be useful to make the API clean.
1Although I don't like that either, it makes the library very limited in multithreaded environments. Still sometimes it makes senes, but you can always have a structure with all the needed data and pass it in every call to the library API. So global variables are very rarely good.
I added a few printf stantments to see if the information is being computer and passed correctly, and while is is being computed correctly in the calcMean function, I keep getting zeros in the main function. I am not sure where my mistake is.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void calcMean(int [], int, float);
void calcVariance(int [], int, float);
int main(void)
{
/*create array and initialize it with values*/
int mainArr [ ] = {71,1899,272,1694,1697,296,722,12,2726,1899,
.......
1652,488,1123,17,290,1324,2495,1221,2361,1244,
813,2716,1808,2328,2840,1059,2382,2391,2453,1672,
1469,778,2639,357,2691,1113,2131,23,2535,1514,
2317,45,1465,1799,2642,557,1846,1824,1144,1468,-1};
/*create initilized values for variables*/
float mean = 0.0;
int counter = 0;
calcMean(mainArr, counter, mean);
calcVariance(mainArr, counter, mean);
printf ("Mean: %10.2f\n", mean); /*gives the average number to one decimal place*/
printf ("counter: %10.0d\n", counter);
getchar();
}/*End of the program*/
void calcMean(int mainArr[], int counter, float mean)/*This function finds the Mean(average) of the function, and the size of the array*/
{
int sentinel = -1;
float sum = 0.0;
int index = 0;
for (index; mainArr[index] != sentinel; index++) /*gets the total numbers in the function and the sum*/
{
counter++;
sum = sum + mainArr[index];
} /*end of the sumation and counting of integers*/
printf ("%0.0d\n", counter);
mean = ((float) sum / counter); /*Divides the sum by the total number of numbers to find the mean*/
printf ("mean: %10.2f\n", mean);
}
void calcVariance(int mainArr[], int counter, float mean)
{
int varindex = 0;
int numerator =0;
int square = 0;
int variance = 0;
int sumation = 0;
for(varindex; varindex<counter; varindex++)
{
numerator = (mainArr[varindex] - mean);
square = (numerator * numerator);
sumation = sumation + square;
variance = sumation / (counter-1);
}
printf ("variance %10.2f\n", variance);
}
You're assuming your function changes the value of outer variables. It won't.
calcMean(mainArr, counter, mean);
^ ^ pass by value
void calcMean(int mainArr[], int counter, float mean)
^ ^ receive by value
Modifying counter inside the function changes only the local variable.
Function parameters are copied into functions. So the variables inside a function will not change the parameters in the outer function.
You will need to do something like the following to any function which you wish to pass back more than one value from a function. (If you only need to pass back one value that can be returned with the function return statement).
// declare the parameters you wish to pass back to calling function as pointers
void calcMean(int [], *int, *float);
// pass the address of the variables:
calcMean(mainArr, &counter, &mean);
// obtain the values of the pointers in your calcMean using derefence operator *
printf ("%0.0d\n", *counter);
*mean = ((float) sum / *counter);
OP later requested an answer with little use of pointers.
As others (#suspectus, #Karoly Horvath, #Carl Norum) correctly pointed out the problem that passing into a function mean does not change it.
main() has an object named mean. That object's value was used to initialize the object called mean in the argument list of calcMean(). calcMean() proceeded to set its mean to some value. At the end of the function, the original mean in main() is not affected.
Instead, use the return value of function calcMean() to set mean in main().
// void calcMean(int mainArr[], int counter, float mean)
float calcMean(int mainArr[], int counter) {
float mean;
...
mean = ((float) sum / counter);
return mean;
}
int main(void) {
...
float mean = 0.0;
...
// calcMean(mainArr, counter, mean);
mean = calcMean(mainArr, counter);
...
}
Do the same for calcVariance
C is a pass-by-value language. Modifying mean and counter in the other functions doesn't affect their values in main().
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)