Calculate Average of 5 Integers Using an Array - c

I can't seem to get it right. The question is "Calculate the Average of 5 Integers using an array"
#include<stdio.h>
#include<stdlib.h>
int main()
{
int avg[5],i,total;
int average;
printf("Enter the marks entered in 5 subjects");
for (i=0; i<5; ++i){
scanf("%d",&avg[i]);
}
for(i=0; i<5; ++i){
total = total + avg[i];
}
average= (float)total/5;
printf("The average of 5 marks is %d",average);
return 0;
}

1) Your answer CAN be a decimal number but you are storing it in an integer which ignores the decimal points.
The variable average should be declared as float average;
The line where you print the result should be changed to printf("The average of 5 marks is %f",average);
2) Initialize the variable total as int total = 0;

In the for loop's first iteration, variable total is used uninitialized, so the result is wrong since it will automatically acquire a garbage value if not initialized explicitly. Take this whole thing:
#include <stdio.h>
int main() {
int avg[5], i, total = 0, average;
printf("Enter the marks entered in 5 subjects");
for (i = 0; i < 5; ++i) {
scanf("%d", &avg[i]);
total += avg[i];
}
average = total / 5;
printf("The average of 5 marks is %d", average);
return 0;
}

You've just declared the variable total but didn't initialize it. So, total contains a garbage value. For that if you add anything to total, the value will not be the correct as expected. It will be added to the garbage value. So,initialize the variable total with 0.
int total=0;
You need not to use type casting. Just declare the average variable as double.
double average=0;
average = total/5.0;
And you should print as printf("The average of 5 marks is %lf", average);

total should be initialized to 0:
int avg[5],i,total=0;

total is a local variable, hence it needs to be initialised. Had it been within file scope (like, a global variable), or a static variable, you might not have to initialise it to 0.
An initialisation could be simply like:
int avg[5], i, total = 0 ;
or
int avg[5], i, total;
total = 0 ;
Why do you need initialisation? Because of this statement:
total = total + avg[i];
Here total is calculated using its previous value. What is total's previous value the first time this statement is encountered? It could be anything, commonly referred to as garbage value, invoking undefined behaviour. Hence, you need initialisation to give this starting value to total. Note, you don't need to initialise average, because its value does not depend on its previous contents.
Another problem is with the concepts of typecasting. Here is the statement:
average= (float)total/5;
You are right about typecasting total to float (you may also have done total/5.0 instead). However, you are storing the result in an integer. This will result in a second typecasting, from the result in float to int.
Hence, you need to declare average as a float.
(Note: If having a float result is not your requirement, and you really need an integral answer, you may ignore this part).

You need to initialize variables before you use them in your code.
What goes WRONG in your code is,
int avg[5],i,total;
where you have not initialized the int variable "total"
Hence this code will use a garbage value
for(i=0; i<5; ++i){
total = total + avg[i];
}
You need this correction
int avg[5], i, total=0;

Related

How to do simple average calculation using a function & calling it?

I need to learn how to use the function for the calculation and then a simple call in main. When I tried it didn't work. I have no idea what to do. It works but when I take out the code from main it gets funky.
this is simple simple scenario and code for that.
Write a function that takes an array of ints, and the size of the array - another int.
It also returns a double. Call this one 'average.' Return a double that is the average
of the values in the array. Demonstrate that it works by finding the average of an array
with these values {78, 90, 56, 99, 88, 68, 92}
#include <stdio.h>
#include <stdlib.h>
// Outside of main, a function will be declared that takes an array of ints.
double Function(int Array[7])
{
// int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
return average;
} // Ends Function
// There will also be the size of the array(which is another int)
// The function will return a double called average. It is the average of the values in the array.
int main()
{
//int i; // Allows us to use the for loop and print each element in the corresponding array.
// int array numbers are declared and initialized.
int Array[7] = {78, 90, 56, 99, 88, 68, 92};
int sum = 0;
int i;
double average;
// This for loop allows us to use all 7 elements in the array.
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
Function(Array);
system("pause");
return 0;
}
Can any one give me a tips!
If you want to follow the instruction you were given, your function declaration should be
double average(int *array, int array_size)
Also, your solution should be general, not only for array with length of 7.
In general in C language - when you want to pass an array which its length is unknown, you pass the address of the array (here *array) and its size (here array_size). Then your function will iterate over the array from the given address, with jumps of the type (here jumps of sizeof(int) because it's an array of ints).
In C Program execution always starts from main.
So the stack will be like
main()-->Function()
You are almost right just you called the function which returns the average so to keep that average or to accept that average in main you need variable so just remove all the code shown below
for(i=0; i<7; i++)
{
// This takes all the array's elements and sums them up.
sum += Array[i];
}
// This prints the sum
printf("Sum = %d\n", sum);
// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);
Now take the results returned by the Function() in average variable shown below.
average=Function(Array);
Now print that value if you want to print or use in main if you need.
the posted code contains several misconceptions
no need to '#include' header files those contents are not needed.
only write code that is part of the solving of the problem. Other code that is added for 'debug' purposes should be eliminated from the final executable. Usually be surrounding the debug code with: #ifndef NDEBUG .... #endif Suggest learning how to work with NDEBUG
The problem only needs to solved once, not both in 'main()' and in 'Function()' BTW: function is a terrible function name suggest: calculateAverage(). Function names should indicate what they will perform, usually by starting the function with some active verb, like calculate
for ease of readability and understanding, consistently indent the code. Indent after every opening brace '{'. unindent before every closing brace '}'. Suggest each indent level be 4 spaces as that is wide enough to be visible even with variable width fonts. Remember, the compiler (in general) doesn't care about the 'style' of the code formatting. However, any human cares a lot, because the human wants to be able to read the code.
it is (almost always) a bad idea to hard code any values other than 0 and 1. Instead give them meaningful names via a enum statement or #define statements, then use those meaningful names throughout the code.
Please pay attention to these 3 details in the code:
how the size of the array is calculated
how the parameters are passed to the 'Function()'
how the average is calculated.
Note: when all the variables in a divide operation are integers, then a integer divide is performed. This can produce some surprising results.
For instance, 5/3 results in 1, not 1.66.
by wanting to keep the fraction, cast one of the elements (not the whole expression) to double or float
and now the code
#include <stdio.h> // printf()
//#include <stdlib.h>
double Function(int *pArray, int numElements );
int main( void )
{
// int array numbers are declared and initialized.
// note: usually best to let the compiler calculate array size
// rather than hardcoding the size
int Array[] = {78, 90, 56, 99, 88, 68, 92};
// number of elements in array
int sizeofArray = sizeof(Array)/sizeof(int);
// call Function to calculate and return as double,
// the average of the array elements
double average = Function( Array, sizeofArray );
// This prints the average as a 'double'.
printf("The resulting average is %lf \n", average);
//system("pause"); // not portable, suggest:
int ch;
while( (ch = getchar()) != EOF && '\n' != ch );
getchar();
//return 0; // <-- in modern C, if main to return 0 then this line not needed
} // end function: main
double Function(int *pArray, int numInts )
{
int sum = 0;
double average;
for(int i=0; i<numInts; i++)
{
sum += pArray[i];
}
// cast one of the values as a double so an integer divide is NOT performed
average = (double)sum / numInts;
return average;
} // end function: Function

What does this mean and how do I rectify it *** stack smashing detected ***: ./array1output terminated

This is the code. Why am I facing this error and what source of information should I refer so as to rectify such errors so that I get to know 'If I do this that way, I will get 'x' error'
#include<stdio.h>
void main()
{
int i,avg,sum;
int marks[30]; // Array declaration
for(i=0;i<31;i++)
{
printf("Enter Marks:");
scanf("%d",&marks[i]); // Stores data in Array
}
for(i=0;i<31;i++)
sum=sum+marks[i];
avg=sum/30;
printf("Average marks of student \t %d",avg);
}
Whenever you declare a variable in a function it allocates memory on the stack. The stack is a reserved memory area for doing temporary data manipulation within the function. Now in your code you declared 3 ints and one array of ints with 30 slots. In your for loop you are putting 31 ints into 30 slots; from 0 thru 30 are 31 numbers. The last number is being put beyond the 30th slot and therefore "smashing" into the next spot on the stack, in other words overwriting it. The solution would be to change you for loop to for(i=0;i<30;i++).
You have declared an int type array as [30] and have tried to assign 31 values to it. Please note that the array starts from 0. So the for loop should be as mentioned below.
for(i=0;i<30;i++)
Hence the issue, Please change the for loop and rest are all fine in your code. Thank you. :)
#include<stdio.h>
void main()
{
int i, avg, sum=0;
int marks[30]; // Array declaration
for (i = 0; i<30; i++)
{
printf("Enter Marks:");
scanf("%d", &marks[i]); // Stores data in Array
}
for (i = 0; i<30; i++)
sum = sum + marks[i];
avg = sum / 30;
printf("Average marks of student \t %d", avg);
}

Adding digits of an integer in C

My program asks the user to input an integer and adds the sum of the digits.
#include <stdio.h>
int main (void)
{
int inputNum, sum;
// Gets the inputNum
printf("Type in a positive integer, and this program\nwill calculate the sums of the digits: ");
scanf("%i", &inputNum);
do
{
sum += (inputNum % 10);
inputNum /= 10;
} while (inputNum != 0);
printf("Your sum is: %i\n", sum);
}
But every time it put an integer in, I get a number around 36000. I saw another example online that used %d, so I tried it but it made no difference. Am I just going in the wrong direction from the start? Thanks in advance.
You never initialized sum; it may well be starting with value 1,000,000
Just do:
int inputNum, sum = 0;
First thing, initialize sum to 0. Try then. int sum = 0;
Do it:
int inputNum, sum = 0;
i.e., you have to initialize sum.
Because in C the value of an uninitialized variable cannot be determinated. The value that you are getting is garbage from memory.
Initialize sum as zero. int variables don't have any default value unless its a global or static variable. as a (non-static) local variable inside of a function, it has an indeterminate value.

calculation of average number get way to high. I don't get why?

I am trying to get the average number of an array but the output is way to high for it to be correct. What am I doing wrong?
int count(int arr[]){
int sum;
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
You need to initialize sum to zero before using it. C or C++ does not do this automatically for you in case of variables with automatic storage duration. It takes "time", and in C or C++ you don't pay for what you don't need. Otherwise you get a junk value (whatever its stored at that memory address, and technically it is undefined behaviour to use un-initialized variables except in assignments).
You also need to initialize the array, like
int arr[100]{}; // C++11 or later
or
int arr[100] = {0}; // C++98 or good old C
then fill it up with values. Do not consider the junk values as "random numbers", since again you are encountering undefined behaviour and the program is not altogether safe.
Undefined behaviour(UB):
sum = sum + arr[i];
You have used sum above and it was not initialized. It is UB to read values of uninitialized variables in C and C++.
Actually given your code it is even once again UB because neither array values arr[i] are initialized.
sum contains garbage value. Do initialize variable sumenter code here.
To verify you can print before updating sum.
Try the following:
int count(int arr[]){
int sum = 0; // <==================== initialize to zero
//Average
for(int i=0;i<100; i++)
sum = sum + arr[i];
printf("Average:%f \n", sum/100);
}
int main()
{
int array[100]; //RANDOM NUMBERS 0-900
count(array);
return 0;
}
Without this initialization, the local variable sum can have any arbitrary initial value. And you will end up with arbitrarily large sum. Which will throw off the average.
The reason for this is that local variables are NOT initialized to zero automatically (unlike global variables).

Trouble making a running total in C

I'm new at programming, new on this site too, so hello...
I'm attempting to obtain a running total for integers one thru 10, but I'm getting gibberish answers and I just can't understand why.
To attempt to find out what was going wrong, I added the
printf(" running total is %d\n", sum);
line to the while loop, but just got more of the same nonsense...
please see http://codepad.org/UxEw6pFU for the results....
I'm sure this has a blindingly obvious solution...I'm just too dumb to see it though!
anyone know what I'm doing wrong?
#include <stdio.h>
int main(void) {
int count,sum,square;
int upto=10;
count = 0;
square = 0;
while (++count < upto) {
square = count * count;
printf("square of %d is %d",count,square);
sum =square + sum;
printf(" running total is %d\n", sum);
}
printf("overall total of squares of integers 1 thru 10 is %d\n", sum);
return 0;
}
You need to initialize sum to 0.
EDIT As others have stated after the fact, the reason you're seeing garbage is because sum isn't initialized and contains whatever is in memory. It can be anything, and your use of it with sum = square + sum is going to add square to the uninitialized value.
You are never initializing the value of sum.
The first time your code runs
sum = square + sum;
The value of sum (on the right side) is an arbitrary number because it has not been initialized. Therefore, the resulting value of sum (on the left side) is that arbitrary number plus square.
Simply add a sum = 0 statement like you have for count and square already.
Right off the bat, you do not initialize 'sum' to anything.
edit: A cleaned up version, though depending on compiler, you might need to enforce C99 mode, otherwise older compilers might not support initial declarations in the for loop.
#include <stdio.h>
int main()
{
const int COUNT_MAX = 10;
int sum = 0;
for ( int i = 1; i <= COUNT_MAX; ++i )
{
sum += i*i;
}
printf("The sum of squares from 1 to 10 is: %d\n", sum);
return 0;
}
Initialize sum with 0, otherwise it contains arbitrary data:
sum = 0;
See: http://codepad.org/e8pziVHm
sum is not initialized
You should do :
sum=0;
and remove
square=0;

Resources