How can I calculate the average for each three consecutive numbers in an array and then to print each result? (in C)
I tried to do this.
#include <stdio.h>
int main() {
int n,v[100],i;
float average;
int sum=0;
scanf("%d",&n);
for (i = 0; i < n; ++i) {
scanf("%d",&v[i]);
}
for(i=0;i<n;i+=3) {
sum=v[i]+v[i+1]+v[i+3];
average=sum/3;
printf("%.2f ", average);
}
return 0;
}
sum/3 is an int division with an int quotient.
To also have a fractional part, use floating point division.
// average=sum/3;
average = sum / 3.0f;
for(i=0;i<n;i+=3) { sum=v[i]+v[i+1]+v[i+3]; risks accessing data out of v[] bounds. v[i]+v[i+1]+v[i+3] are not consecutive. I'd expect v[i]+v[i+1]+v[i+2]
for (i = 0; i + 2 < n; i += 3) {
sum = v[i] + v[i+1] + v[i+2];
No good reason to use float. Use double unless float is needed for space/ maybe speed, etc.
Also avoid overflow and precision loss.
for(int i = 0; i+2 < n; i += 3) {
double sum = 0.0 + v[i] + v[i+1] + v[i+2]; // Addition here uses FP math.
double average = sum/3.0;
printf("%.2f ", average);
}
Better code writes a '\n' at the end and does not end with a dangling " ".
const char *separator = "";
for(int i = 0; i+2 < n; i += 3) {
...
printf("%s%.2f ", separator, average);
separator = " ";
}
printf("\n");
Related
The question was to add first seven terms of the following series using for loop
1/1! + 2/2! + 3/3! ....
I thought i might be loosing decimal point due to int but i am not even getting wrong answer.
I ran the code in terminal but it just keeps running no output.
Thanks for helping out.
#include<stdio.h>
int main()
{
int n;
float a;
float v=0.0;
for(n=1;n<=7;n++)
{
a=1.0;
while(n>0)
{
a=a/n;
n--;
}
v=v+n*a;
}
printf(" sum is %f ",v);
return 0;
}
#include <stdio.h>
int fact(int n) {
int product = 1;
for (int i = 1; i < n+1; i++) {
product *= i;
}
return product;
}
int main() {
double sum = 0.0;
for(int i = 1; i < 7+1; i++) {
sum += double(i) / fact(i);
}
printf("Sum is %f\n", sum);
return 0;
}
The series is 1/1! + 2/2! + .. n terms can be written as 1 + 1/1! + 1/2! + 1/3! + ...(n-1) terms .
So it is 1 + sum of 1/i! where i=1 to i=n-1 terms.
So I have taken sum=1 as initial value.
#include <stdio.h>
//this is the function for calculating n!
int fact(int n) {
int product = 1;
for (int i = 1; i < n+1; i++) {
product *= i;
}
return product;
}
int main() {
int n=5;
//we are taking sum=1 as initial value
double sum = 1.0;
//now we run 1/1! + 1/2! + 1/3! + 1/4! i.e. upto (n-1) terms (here n=5 => so n-1 = 4)
for(int i = 1; i < n; i++)
{
sum += (1.0) / fact(i);
}
printf("Sum is %f\n", sum);
return 0;
}
As #DeBARtha mentioned in the original code i was incrementing and then decreasing n causing to loop to run repeatedly.
By using one more variable (m) for the while loop and then decreasing it while increasing the 'n' in the for loop the problem gets resolved.
#include<stdio.h>
int main()
{
int n,m;
float a;
float v=0.0;
for(n=1;n<=7;n++)
{
m=n;
a=1.0;
while(m>0)
{
a=a/m;
m--;
}
v=v+n*a;
}
printf(" sum is %f ",v);
return 0;
}
I tackled the problem by first figuring out the length of two given numbers and aligning the one with less digits (if one exists) into a new array so that the ones, tens, hundreds etc. align with the bigger number's ones, tens, hundreds, etc.
Then I wanted to save the sum of each two aligned elements (with a mod of 10) into a new array while checking if the sum of digits is greater than 10 - just the basic sum stuff. Now the problem occurs with adding two elements into the aplusb integer and I've tried fixing it with writing
int aplusb = (lengthA[max-i]-'0') +(temp[max-i]-'0');
but it doesn't work. I'm stuck and I don't know what to do. Please help.
The whole code:
#include <stdio.h>
#include <math.h>
int main(){
char a[10000];
char b[10000];
scanf("%s %s", &a, &b);
char sum[10000];
int lengthA = 0;
int lengthB = 0;
int i = 0;
while(a[i]){
i++;
} lengthA = i;
i = 0;
while(b[i]){
i++;
} lengthB = i;
char temp[10000];
int aplusb;
int carry = 0;
int max = lengthA;
int difference = abs(lengthA - lengthB);
if(lengthA>lengthB){
for(i=0; i<lengthA; i++){
temp[i+difference]=b[i];
}
for(i=0; i<=max; i++){
aplusb = lengthA[max-i]+temp[max-i]; //<-- this is the problematic line
if(carry = 1) aplusb++;
if(aplusb>9){
carry = 1;
aplusb%=10;
}
sum[i]=aplusb;
}
}
for(i=0; i<=max; i++){
printf("%c", sum[i]);
}
/*
if(lengthB>lengthA){
max = lengthB;
for(i=0; i<lengthB; i++){
temp[i+difference]=a[i];
}
}*/
return 0;
}
Doing operations and storing on very large numbers is very akin to doing operations and storing polynomials, i.e. with x = 10. a0 + a1.10 + a2.10^2 ... + an.10^n.
There are many polynomial libraries on the Internet, where you could find inspiration. All operations on your very large numbers can be expressed in terms of polynomials. This means that by using base 2^8, or even base 2^63, instead of base 10 to internally store your large numbers you would greatly improve performance.
You must also normalize your coefficients after operations to keep them positive. Operations may result in a negative coefficient, That can easily be fixed, as it is very similar to borrowing after a subtraction, this means coefficients must be larger than your base by 1bit.
To convert back to base 10, you'd need to solve r (your result) for v (your value), such as r(10)=v(2^63). This has only one solution, if you enforce the positive coefficients rule.
[note] After thinking about it some more: the rule on positive coefficients may only be necessary for printing, after all.
Example: adding. no memory error checking
int addPolys(signed char** result, int na, const signed char* a, int nb, const signed char* b)
{
int i, nr, nmin, carry, *r;
nr = max(na, nb) + 1;
nmin = min(na, nb);
r = malloc(sizeof(signed char) * (na + nb + 1));
if (nb < na)
{
nr = nb;
}
for (i = 0; i < nmin; ++i)
{
r[i] = a[i] + b[i];
}
for (; i < na; ++i)
{
r[i] = a[i];
}
for (; i < nb; ++i)
{
r[i] = b[i];
}
r[nr - 1] = 0;
// carry - should really be a proc of its own, unoptimized
carry = 0;
for (i = 0; i < nr; ++i)
{
r[i] += carry;
if (r[i] > 10)
{
carry = r[i] / 10;
r[i] %= 10;
}
else if (r[i] < 0)
{
carry = (r[i] / 10) - 1;
r[i] -= (carry * 10);
}
else
carry = 0;
}
// 'remove' leading zeroes
for (i = nr - 1; i > 0; --i)
{
if (r[i] != 0) break;
}
++i;
*result = r;
if (i != nr)
{
*result = realloc(i * sizeof(signed char));
}
return i; // return number of digits (0 being 1 digit long)
}
That code is working now for any two positive numbers with up to ten thousand digits:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(){
char chara[10000];
char charb[10000];
scanf("%s %s", &chara, &charb);
int lengthA = strlen(chara);
int lengthB = strlen(charb);
int max = lengthA;
if(lengthB>lengthA) max=lengthB;
int dif = abs(lengthA - lengthB);
//ustvari int tabele
int a[max];
int b[max];
int sum[max+1];
// nastavi nule
int i;
for(i=0; i<max; i++){
a[i] = 0;
b[i] = 0;
sum[i] = 0;
} sum[max] = 0;
//prekopiraj stevila iz char v int tabele &obrni vrstni red
for(i=0; i<lengthA; i++){
a[i] = chara[lengthA-i-1]-'0';
}
for(i=0; i<lengthB; i++){
b[i] = charb[lengthB-i-1]-'0';
}
int vsota;
int prenos = 0;
for(i=0; i<max; i++){
vsota = a[i]+b[i] + prenos;
if(vsota>=10) prenos = 1;
else if (vsota<10) prenos = 0;
sum[i]=vsota%10;
}
if(prenos==1){
sum[max] = 1;
for(i = max; i>=0; i--){
printf("%d", sum[i]);
}
} else {
for(i = max-1; i>=0; i--){
printf("%d", sum[i]);
}
}
return 0;
}
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
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];
}
//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++;