Array additions and averages - c

So this weeks homework is to: 'Write a program that inputs 6 integers and puts them into an Array. The program
then prints out the following: A list of all Array elements, from 0 to 5 and the sum and
mean value of all elements. NB The mean value of the array elements will not
necessarily be an integer. In order to convert an integer into a real (float) use
casting:
To turn the integer ‘x’ into a float use float(x)
E.g.:
Average = float(sum)/number of elements ;
(In this case the number of elements is 6)'
Not quite sure what I am doing wrong here but my code seems to give back incorrect answers and I can't figure out why.
Any suggestions would be greatly appreciated. I feel like I am going to fail this module as I have struggled with it since the introduction of functions, etc.
Anyway, here is my code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int numArr[5];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + i;
}
avg = sum /6;
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}

'Write a program that inputs 6 integers
int numArr[5];
^^^^^
Change this loop
for (i = 0; i < 6; i++) {
sum = sum + i;
}
like
for (i = 0; i < 6; i++) {
sum = sum + numArr[I];
}
And change this statement
avg = sum /6;
the following way
avg = ( float )sum /6;
And you forgot to output all elements of the array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
and you may remove header <math.h> because neither declaration is used from this header in your program.

Your array isn't large enough to hold 6 numbers.
Change
int numArr[5];
to
int numArr[6];
Currently, you are accessing the array out-of-bunds, resulting in undefined behaviour.
There are couple other problems too:
1) You are not summing the array elements
2) You are doing integer division
Fix it, it'd look like:
#include<stdio.h>
#include<math.h>
int main(void) {
int numArr[6];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + numArr[i]; /* was summing `i` instead of numArr[i] */
}
avg = sum /6.0; /* was doing integer division */
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}

sum = sum + i;
should be
sum = sum + numArr[i];
Array elements should be added.
Later
avg = sum/6.0

for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
avg = (float)sum /6;
Notice numArr[i]

int numArr[5];
should be
int numArr[6];
and
for (i = 0; i < 6; i++) {
sum = sum + i;
}
should be
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
and
avg = sum /6;
should be
avg = sum/6.0 //because division of integer by an integer results by integer value. So we divide integer with a float (6.0) value

Related

Program to print sum of primes in C

#include <stdio.h>
#include <math.h>
int main() {
int n, count, sum;
printf("Enter upper bound n \n");
scanf("%d", &n);
for (int a = 1; a <= n; a++) {
count = 0;
sum = 0;
for (int i = 2; i <= sqrt(a); ++i) {
if (a % i == 0) {
count++;
break;
}
}
if (count == 0 && a != 1) {
sum = a + sum;
}
}
printf("%d", sum);
}
The program is my attempt to print summation of primes < n. I am getting sum = 0 every time and I am unable to fix this issue.
The reason you do not get the sum of primes is you reset the value of sum to 0 at the beginning of each iteration. sum will be 0 or the value of the n if n happens to be prime.
Note also that you should not use floating point functions in integer computations: i <= sqrt(a) should be changed to i * i <= a.
The test on a != 1 can be removed if you start the loop at a = 2.
Here is a modified version:
#include <stdio.h>
int main() {
int n = 0, sum = 0;
printf("Enter upper bound n: \n");
scanf("%d", &n);
// special case 2
if (n >= 2) {
sum += 2;
}
// only test odd numbers and divisors
for (int a = 3; a <= n; a += 2) {
sum += a;
for (int i = 3; i * i <= a; i += 2) {
if (a % i == 0) {
sum -= a;
break;
}
}
}
printf("%d\n", sum);
return 0;
}
For large values of n, a much more efficient approach would use an array and perform a Sieve of Eratosthenes, a remarkable greek polymath, chief librarian of the Library of Alexandria who was the first to compute the circumference of the earth, 2300 years ago.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = 0;
long long sum = 0;
if (argc > 1) {
sscanf(argv[1], "%i", &n);
} else {
printf("Enter upper bound n: \n");
scanf("%i", &n);
}
// special case 2
if (n >= 2) {
sum += 2;
}
unsigned char *p = calloc(n, 1);
for (int a = 3; a * a <= n; a += 2) {
for (int b = a * a; b < n; b += a + a) {
p[b] = 1;
}
}
for (int b = 3; b < n; b += 2) {
sum += p[b] * b;
}
free(p);
printf("%lld\n", sum);
return 0;
}
Error about sum getting set to zero inside the loop has been already pointed out in previous answers
In current form also, your code will not return zero always. It will return zero if value of upper bound is given as non prime number. If prime number is given as upper bound, it will return that number itself as sum.
As mentioned in comment you should initialize sum before first loop something like
int n, count, sum=0;
or you can initialize sum in the loop like
for(a=1,sum=0;a <= n; a++)
and remove sum=0; inside the first loop because it changes sum to 0 every time first loop executes. You can check this by inserting this lines to your code
printf("Before sum %d",sum);
sum = 0;
printf("After Sum %d",sum);
make sure sure that if you are initializing sum in the loop, define "a" in outer of the loop if not the sum goes to local variable to for loop and it hides the outer sum.

How can I make a function and get cumulative sum of previous numbers?

What I want to do is to get a cumulative sum of previous integers starting from 1, for example:
If my input is 4, then the function should work in this way;
1 + (1+2) + (1+2+3) + (1+2+3+4) = 20.
And the output needs to be 20. Also, I have to get this done by a function, not in main(); function while using int n as the only variable.
What I've tried is to make a function which adds from 1 to integer N, and use 'for'to make N start from 1, so that it can fully add the whole numbers until it reaches N.
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
sum = 0;
scanf("%d", &n);
for (n = 0; n <= input; n++) {
sum += n;
}
printf("%d", sum);
return 0;
}
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
What I expected when the input is 4 is 20, but the actual output is 10.
I would have written it this way, remarks are where changes been made
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
// sum = 0; // no need for this
scanf("%d", &n);
/* the next for has no use
for (n = 0; n <= input; n++) {
sum += n;
} */
// I would be adding some input sanitazing if possible here
printf("%d", sum(n));
return 0;
}
int sum(int n) {
int i, /*n, */ rsum = 0; // n is already a parameter, rsum for running sum
// scanf("%d", &n); // nope nope, scanf and printf should be avoided in functions
for (i = 1; i <= n; i++){ // changed i +=1 with i++ , easier to read
for (j=1;j<=i;j++) // need this other loop inside
rsum += j;
}
return rsum;
}
Here it is with a single loop; very fast.
#include <stdio.h>
int cumulative_sum(int m)
{
int sum = 0;
for(int n=1; n<=m; ++n) sum += n*(n+1);
return sum/2;
}
int main(void)
{
int n;
printf("Input value N: ");
scanf("%d", &n);
printf("Answer is %d\n", cumulative_sum(n));
return 0;
}
The main issue is in the function, you are doing only 1 loop (you have also some logical things, which compiler should tell you, like same naming of variable and function.. eg.),
so in case you will put 4 as the input, loop will do only 1+2+3+4, but your case if different, you want to make suma of all iterations like 1 + (1+2) + (1+2+3) + (1+2+3+4)
you are doing only last step basically (1+2+3+4), 4 iterations (4x suma), but actually you need 10 iterations (due suma of all particular suma of elements)
As suggested, try to debug your code - What is a debugger and how can it help me diagnose problems?
- it will really help you do understand your code
As mentioned, the issue is in
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
You have to make two loops eg. like follows:
int sum,n = 0;
//scanf("%d", &n);
n = 4; //input simulation
//just for demonstration
int iterations = 0;
//counter for total loops (how many "brackets" needs to be count)
for(int loopsCounter = 1; loopsCounter <= n;loopsCounter++){
//counter for child elements in brackets (like 1+2 ,1+2+3, ..)
for (int sumaLoopCounter = 1; sumaLoopCounter <= loopsCounter; sumaLoopCounter++){
//simply make sum with the given number
/* first step 0 +1
second 1+2 added to previous suma = 1+3
third 1+2+3,.. added to previous = 4+6
...
*/
sum += sumaLoopCounter;
//just testing for demonstration
iterations++; //iterations = iterations + 1
}
}
printf("%i \n",iterations);
printf("%i",sum);
Then you got output as expected - sum of all "bracket elements" and 10 iterations, which matches numbers of needed additions
10
20

Finding the average of an array using c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am new to coding in C and I am trying to get the average of the array but for some reason it is not calculating, it is giving me a result of 0.0.
How can I fix this. Thanks
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i <= 7; i++){
sum = sum + grades[7];
}
average = sum/7;
return average;
}
The output is:
Average is: 0.00
Minimum change solution:
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
Change for(i = 0; i <= 7; i++){ to for(i = 0; i < 7; i++){. Valid indicies for grades are only 0-6. 7 is out of bounds.
Change sum = sum + grades[7]; to sum = sum + grades[i]; You need to check each element, not the (beyond) last one over and over.
Change average = sum/7; to average = sum/7.f; The .f ensures no integer division. That preserves the decimal during division.
I hope that helps!
Here is full code. with 2 changes, Line 20 and Line 23
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
/*Changed here to <7 because i takes 0,1,2,3,4,5,6 which are 7 elements, your code is <=7 which takes 0.......7 which are 8 elements */
for(i = 0; i < 7; i++){
/*Changed here to i from 7, your code everytime sums out of bound element, Garbage value since grades[7] does not exist*/
sum = sum + grades[i];
}
average = sum/7;
return average;
}
Change for(i = 0; i <= 7; i++){} to for(i = 0; i < 7; i++){}, because
totally you have 7 elements, starting from 0to6.
Change sum = sum + grades[7]; to sum = sum + grades[i];, as grades[7] will only have the last value of the array, but you want to add all the values present in the array.
include
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
Hope that helps..
Try by putting i in place of 7,
sum = sum + grades[7];
like
sum = sum + grades[i];
and your loop from 0 to 6
In place of using this
sum = sum + grades[7];
Use
sum = sum + grades[i];
Then it will work.

C program- find the lowest student score above, and the highest score below the boundary

I am finishing a program where I read in a bunch of non-negative doubles into an array, then calculate the mean and stand dev of the values. Then the mean plus the stand dev represents getting a B.
I am having trouble with the next part, where I need to find the lowest score from the array of numbers that will give me a B, and then the highest value in the array that did not get a B. I am having so much trouble with this part that any help would be amazing.
I also have to make the program stop when EOF is typed into it, but I can not figure that part out either, so any help with that would also be appreciated. For now I instead just made it work for all positive values and stop when a negative value is introduced, here is my code:
#include <stdio.h>
#include <math.h>
int main () {
int arr[100];
int y, x;
int i;
double mean = 0;
double std = 0;
double this = 0;
i = 0;
printf("Enter next number, EOF to stop > ") ;
scanf("%d",&x);
while (x >= 0) {
arr[i++] = x;
printf ("Enter next number, EOF to stop > " );
scanf("%d",&x);
}
y = i;
double sum = 0;
double sum1= 0;
for(i = 0; i < y; i++){
sum = sum + arr[i];
}
mean = sum / y;
for (i = 0; i < y; i++){
sum1 = sum1 + pow((arr[i] - mean), 2);
}
std = sum1 / ((float)y - 1);
this = mean + sqrt(std);
if (10 > y) {
printf("**You must enter atleast 10 scores***\n");
return 0;
}
printf("Mean = %.2lf, Standard Deviation = %.2lf\n", mean, sqrt(std));
printf("Scores above %.2lf get a B\n", this);
return 0;
}
Code:
#include <stdio.h>
#include <math.h>
int main () {
int arr[100];
int y, x;
int i;
double mean = 0;
double std = 0;
double margin = 0;
i = 0;
printf("Enter next number, EOF to stop > ") ;
scanf("%d",&x);
while (x >= 0) {
arr[i++] = x;
printf ("Enter next number, EOF to stop > " );
scanf("%d",&x);
}
y = i;
if (10 > y) {
printf("**You must enter atleast 10 scores***\n");
return 0;
}
double sum = 0;
double sum1= 0;
for(i = 0; i < y; i++){
sum = sum + arr[i];
}
mean = sum / y;
for (i = 0; i < y; i++){
sum1 = sum1 + pow((arr[i] - mean), 2);
}
std = sum1 / ((float)y - 1.0);
margin = mean + sqrt(std);
printf("Mean = %.2lf, Standard Deviation = %.2lf\n", mean, sqrt(std));
printf("Scores above %.2lf get a B\n", margin);
int below = arr[0]; // highest value in the array that will not get a B
int above = arr[0]; // lowest value in the array that will give a B
for (i=0; i<y; i++) {
if ((arr[i] > below) && (arr[i] < margin)) {
below = arr[i];
}
else if ((arr[i] > margin) && (arr[i] < above)) {
above = arr[i];
}
}
return 0;
}
First of all, if you intend to program in -ansi -pedantic C, all variables must be defined at the top of the block. e.g:
Correct:
func() {
variable v1;
variable v2;
perform_stuff();
}
In correct:
func() {
perform_stuff()
variable v1;
}
and now to your question:
if you wish to hold an array of double values, the array should be of type double and not of the type - int.
to find the lowest number in the array:
There are few possible options for that one, first, you could ask the user to enter the values from lowest to highest and then just reach to the array[0] (first location = lowest value). but if you do not/ can not, always use quicksort: http://www.cquestions.com/2008/01/c-program-for-quick-sort.html
to sort the array from lowest values to the highest and then find the value you wish using a binary search: http://www.cquestions.com/2008/01/c-program-for-binary-search.html
to search for the value you wish to.
or you could also make it work this way in the efficiency of O(N):
int heighest_smaller_than_mean = 0;
int smallest_smaller_than_mean = mean;
for(i = 0; i < mean; i++) {
if(heighest_smaller_than_mean < arr[i])
heighest_smaller_than_mean = arr[i];
if(smallest_smaller_than_mean < arr[i])
smallest_smaller_than_mean = arr[i];
}
Hope I understand you correctly :)
For the second question, do not read in the input using fscan(%d, &x), rather create a character array (for example, char [] str = new char[5];) and scan that with fscan(%s, &str). Then, compare the string to another string containing "EOF" using if (strcmp(str, eofStr) == 0) break. Use atoi to convert the string to an integer.
To find the lowest score with a B, store an integer that saves the lowest number with a B. Set the initial value to the A grade value. Iterate through the loop and compare to a score for each iteration. If the score is lower, but still a B, exchange the current lowest score with this score. Finish the loop and you will have the lowest score with a B. You can do the same thing to get the highest score without a B.
int low = this + sqrt(std);
for (int i = 0; arr[i] > 0; i++) {
if (low > arr[i] && arr[i] >= this) low = arr[i];
}

Why is my product cost average coming out at 0?

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders.
//Program written using multiple functions.
#include <stdio.h>
#define SIZE 5
void inputData();
void processingData(float costs[]);
float costs[5];
float sortedCosts[5];
int main()
{
inputData();
processingData(costs);
}
void inputData()
{
int i = 0;
printf("\nPlease enter five products costs.\n");
while (i < 5)
{
scanf("%d", &costs[i]);
i = i + 1;
}
}
void processingData(float costs[])
{
int i;
int j;
float sum = 0.00f;
float average = 0.00f;
for (i = 0; i < 4; ++i)
{
int j, min, temp;
min = i;
for (j = i + 1; j < 5; ++j)
if (costs[j] < costs[min])
min = j;
temp = costs[i];
costs[i] = costs[min];
costs[min] = temp;
}
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
sortedCosts[i] = costs[i];
for (i = 0; i < 5; ++i)
sum += costs[i];
average = sum / 5;
printf("Product Cost Average = %.2f\n", average);
}
Why is my product cost average coming out as zero? As far as I can see all of my variables are declared as float? I have tried all sorts of combinations and I cant seem to get it to work. I really appreciate your help!
scanf("%d", &costs[i]);
cost[i] is of type float in your program not int.
Use %f conversion specification to read a float.
Also:
temp = costs[i];
Your temp value is of type int but costs[i] is of type float. I don't think it is deliberate.
Use the "%f" modifier in scanf to get a float, rather than "%d".
Also, you
#define SIZE 5
but you use 5's throughout your code rather than SIZE. Use SIZE to reduce the possibility of bugs.
There's nothing wrong with
i = i + 1;
but that is much more commonly written as
i++;

Resources