c program to find average - c

i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.
#include <math.h>
#include <stdio.h>
int main()
{
int n;
float per1, per2, per3;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for (int i = 0; i <= n - 1; i++)
{
if (arr[i] < 0)
{
int sum1 = sum1 + 1;
}
if (arr[i] > 0)
{
sum2 = sum2 + 1;
}
else
{
sum3 = sum3 + 1;
}
}
per1 = sum1 / n;
per2 = sum2 / n;
per3 = sum3 / n;
printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);
return 0;
}
output
3
1
-2
0
0.000000
0.000000
0.000000
the last three numbers should be .3,.3,.3 but it is giving zeros.

I think this code is a little bit better. I've used the function malloc() instead of the "scattered" declaration int arr[n] (in this case I prefer the old C style).
People already said you the problem relevant to the variable types and some ways to solve the problem. Here there's another way similar to the others you just saw between the answers.
#include <math.h>
#include <stdio.h>
#include <malloc.h>
#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"
int main()
{
int n, *arr=NULL;
float per1,per2,per3;
int sum1=0;
int sum2=0;
int sum3=0;
printf("How many number you have to insert? ");
scanf("%d",&n);
if (n<=0)
return 1;
arr=malloc(n*sizeof(*arr));
if (arr==NULL)
return 2;
printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
for(int i = 0; i < n; i++){
printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
scanf("%d",&arr[i]);
}
for(int i=0;i<=n-1;i++)
{
if(arr[i]<0){
sum1=sum1+1;
} else if(arr[i]>0){
sum2=sum2+1;
} else {
sum3=sum3+1;
}
}
per1=sum1; per1/=n; per1*=100.0;
per2=sum2; per2/=n; per2*=100.0;
per3=sum3; per3/=n; per3*=100.0;
printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);
if (arr!=NULL)
free(arr);
return 0;
}

Do floating point arithmetic like this
per1=sum1/(1.0*n);
per2=sum2/(1.0*n);
per3=sum3/(1.0*n);

How do you calculate percentage of some value? Your answers shouldn't be 1,1,1 but 33%, 33%, 33% for input you have. So your code should instead of this
per1=sum1/n;
be like this
per1=sum1*100.0/n;
And you have also got wrong your if conditions. The else part is tied only to second if. So every number less or equal to 0 is counted into sum3 which is not what you probably meant. So your
if (arr[i] > 0)
should have been
else if (arr[i] > 0)
And one last thing. On this line you are creating completely new variable sum1 that will live only to the end of the if statement and thus will not appear in the final calculation. I will leave it to you how to fix it.
int sum1 = sum1 + 1;
I don't know what environment you are using for development, but you should learn how to use debugger from the beginning. You can then peek into flow of your code to see what is going on and when it went wrong. With simple programs like this it is really easy. If you are on Visual Studio, they have really nice debugger integrated. Just set breakpoint and run Debug. If you are on Linux, there is gdb which might come pretty rough for beginners, but there are also graphical tools like ddd.

Since both sum1 and n are integers, the result of sum1/n is also an integer. This means that if sum1 is less than n, then the result of sum1 / n is 0.
To get a floating point result, at least one of the operands has be be float or double. I suggest you declare your sum variables to be double instead of int.

Related

Recursion in C: why does my simple code doesn't work?

Given i the value of 3, the output should be the sum of 3/(3+1) + 2/(2+1) + 1/(1+1), always stopping on 1.
I can't seem to figure out what's wrong with what I did, thank you for your attention.
#include <stdio.h>
#include <math.h>
int sum_recur(int i) {
if (i > 1) {
return sum_recur(i - 1) / (sum_recur(i - 1) + 1);
} else {
return 1;
}
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%d \n", sum_recur(i));
}
I think this would be the right recursive implementation of your formula
int sum_recur(int i){
if(i >= 1){
return (i / (i + 1)) + sum_recur(i-1);
} else{
return 0;
}
}
Also, as #atirit mentioned, you should consider making the output to be float or double in order to preserve the floating points values of the division result. Otherwise, the result of sum_recur will always be 0 since i / (i + 1) is always 0 for integer type
#include <stdio.h>
#include <math.h>
float sum_recur(int i){
if(i >= 1){
return (i / (i + 1.0)) + sum_recur(i-1);
} else{
return 0;
}
}
int main(void){
int i;
printf("Inform a number:\n");
scanf("%d",&i);
printf("%f \n",sum_recur(i));
}
Here's what I believe you're trying to implement, no need for recursion, but it's there if you need it:
#include <stdio.h>
double sum_recur(double i) {
if (i < 1) return 0;
return i / (i + 1) + sum_recur(i - 1);
}
double sum_iter(double i) {
double sum = 0;
for (; i >= 1; i--) {
sum += i / (i + 1);
}
return sum;
}
int main(void) {
int i;
printf("Inform a number:\n");
scanf("%d", &i);
printf("%f \n", sum_iter((double) i));
printf("%f \n", sum_recur((double) i));
}
The summary is this:
There's no need for the math library.
Use float or double and not int - in the code itself and in the printf.
Correct the logic in the recursion.
It can be solved iteratively quite nicely.
I don't understand what are you trying to achieve from this code. The code that you've written will always return 2.
sum_recur will always stop at 1 and you return statement will calculate 1/1+1, which is always 2. For input 3, the sum_recur will generate following:
sum_recur reaches 1 and hence returns 1 for input value 2
1/1 + 1 = 2, so for i=2 sum_recur will again return 2
This is will go on for any input number. This is why no matter what the input is, output of this recursion will always be 2. Further, what you expect this function to do in your question statement is not possible if you're using division between recursion calls. The result that you're looking to achieve is simply addition of 2 n-times or multiplication of 2 with n.
The answers written here explain the problem reasonably well, I just want to add a little bit on your code specifically,
While you do f(i-1)/f(i-1)+1 this is a terrible way of doing this and in case of a larger seed input this might cause you runtime problem with stackoverflow. So I suggest you should try something that's more efficient if at all you have to use recusion. Like this by storing the fun call value
int n = f(i-1);
return n/n +1;

Imprecise average at run time

I am trying to solve a problem and I've run into a bit of an issue.
I have to find the running average of a series of numbers.
Example:
input 4 2 7
output 4 3 4.3333
Now here's the problem although I get the answer, it is not the precise answer.
Accepted Output: accuracy difference shown in the image
290.6666666667
385.4000000000
487.8333333333
477.4285714286
496.4444444444
...
523.8571166992
506.0454406738
495.3043518066
I can't find whats wrong. Some help would be highly appreciated.
#include<stdio.h>
main(){
int n;
printf("set:");
scanf("%d",&n);
float arr[n+1],resarr[n+1];
float sum=0;
for(int i=1; i<=n; i++){
scanf("%f",&arr[i]);
sum=arr[i]+sum;
float res= sum/(float)i;
resarr[i]=res;
}
int i=1;
while(i<=n) {
printf("%0.10f\n",resarr[i]);
i++;
}
return 0;
}
Here
for(int i=1; i<=n; i++){ }
you are trying to access out of bound array elements, this certainly causes undefined behavior as let's assume if n is 5 then you are accessing arr[5] also which doesn't exist.
C doesn't perform array boundary condition check, its programmer responsibility to not to access out of bound elements else it causes UB.
In C array index starts from 0 not from 1. So better start rotating loop from 0 to n. For e.g
for(int i=0; i<n; i++) {
scanf("%f",&arr[i]);
/* some code */
}
Code fails to achieve the desired accuracy as it is using float rather than double. #Some programmer dude
Typical float is precise to 1 part in 223. For printing to 0.0000000001, better to use double which is typically precise to 1 part in 253.
#include<stdio.h>
int main(void) {
//float arr[n + 1], resarr[n + 1];
//float sum = 0;
double arr[n + 1], resarr[n + 1];
double sum = 0;
...
// scanf("%f", &arr[i]);
scanf("%lf", &arr[i]);
...
// float res = sum / (float) i;
double res = sum / i; // cast not needed as `sum` is `double`
...
}
Iterating from 1 is not idiomatic in C. More common to iterate starting at 0.
size_t is best for array sizing and indexing. int may be too narrow. Of course with small arrays, it makes scant difference.
#include<stdio.h>
int main(void) {
printf("set:");
size_t n;
scanf("%zu", &n);
double arr[n], resarr[n];
double sum = 0;
for (size_t i = 0; i < n; i++) {
scanf("%lf", &arr[i]);
sum = arr[i] + sum;
double res = sum / (i+1);
resarr[i] = res;
}
for (size_t i = 0; i < n; i++) {
printf("%0.10f\n", resarr[i]);
}
return 0;
}
More robust code would check the input from the user it insure it is valid, allocate rather than use a VLA if n is allowed to be large, flush output before reading, etc.
Note that array arr[] is not needed, just a single double for the input and sum.

Factorial as a sum of consecutive number

I was recently solving a problem "No. of ways to express factorial of a number as sum of consecutive number"
My solution is :
int fact_as_sum(int n) { // n is the number whose factorial need to be taken
long int fact=1;
int temp=0,count=0;
for(int i=n;i>0;i--){
fact*=i;
}
printf("%d\n",fact);
for(int i=fact/2;i>0;i--) {
int j=i;
temp=fact;
while(temp>=0) {
if(temp==0) {
count++;
break;
}
else
temp-=j;
j--;
}
}
return count;
}
The solution works correct till small no. of 10!.
But my solution has high complexity.
Can anyone suggest a less complex solution ?
Thanks
Ok, so this problem tickled my brain a lot, so first of all thank you for that, I love to solve these kind of problems!
I started with a math analysis of the problem in order to find the best implementation, and I came up with this solution:
By defining n as the factorial result number, m the number of sums to be performed and x the starting number for the addition, it all breaks down to the following formula:
.
This can now be simplified, resulting in the following formula:
.
That can be also simplified, giving the following result:
.
Solving for x (the starting number for addition), results in:
.
It is now possible to iterate for all the values of m to find the wanted x value. the lower bound for m is for sure 0, it is not possible to add a negative quantity of numbers! The top bound can be found by noticing that x should be a positive number, it would have no sense to consider negative values that will be nulled by the corresponding positive part! This gives the following result:
That yields the following result:
The negative value of m is discarded as previously said.
This translates in the following C code:
#include <stdio.h>
#include <math.h>
void main() {
int fact = 8; //select the wanted factorial to compute
float n = 1;
int i;
float x;
float m;
printf("calculating %d factorial...\n", fact);
for (i = 2; i < fact + 1; i++) {
n *= (float)i;
}
printf("the factorial result is %d\n", (int)n);
printf("calculating the sum of consecutive numbers...\n");
//compute the maximum number of iterations
int maxIter = (int)((-1 + sqrt(1 + 8 * n)) / 2);
for (i = 0; i < maxIter; i++) {
m = (float)i;
//apply the formula
x = (n / (m + 1)) - (m / 2);
if (x - (float)((int)x) == 0) {
printf("found a correct sum!\n");
printf("the starting number is: %d\n", (int)x);
printf("the number of sums is: %d\n", i + 1);
}
}
}
I've tried this solution on a couple of values and wrote the code for the test, the results seem right. There is an issue with the factorial though, since the factorial reaches very high values quickly, memory needs to be managed better.
Hope I gave an interesting solution, I had fun solving it!
Please correct in case there are problems with this solution.
Sure. I may try and give a simpler solution for finding the count: replace
temp = fact;
while(temp>=0) {
if(temp==0) {
count++;
break;
}
else
temp-=j;
j--;
}
by
if ( fact % j == 0 )
count++;
. This also means you don't need temp, since you can use the remainder operator (%) to check for whether j is a divisor (that's what you tried to do in that while loop, right?).
Fist of all, your code has a bug.
1. You need to change i=fact/2 in for loop to i=(fact+1)/2;
2. You need to add j > 0 condition in while loop to prevent infinite loop. Because for example temp-(-1) will increment temp.
Fixed code:
for(long int i=(fact+1)/2; i>0; i--) {
long int j=i;
temp=fact;
while(j > 0 && temp > 0) {
temp-=j;
j--;
if(temp == 0) {
count++;
break;
}
}
}
As of your question, it can be done in O(sqrt(2*N)) time. Here are some understandable, clean answers:
long int count = 0;
for (long int L = 1; L * (L + 1) < 2 * fact; L++) {
float a = (1.0 * fact-(L * (L + 1)) / 2) / (L + 1);
if (a-(int)a == 0.0)
count++;
}
https://www.geeksforgeeks.org/count-ways-express-number-sum-consecutive-numbers/
https://math.stackexchange.com/questions/139842/in-how-many-ways-can-a-number-be-expressed-as-a-sum-of-consecutive-numbers

|c| Series 1+2x+3x^2+4x^3+....nx^(n-1)

First of all, I searched and all questions I found are similar but not exactly this one.
This is my first post here, I'm a beginner in programming and currently learning to code in C.
Been struggling with this code for about 5 hours now.
The question is create a program in C, using only loops (and not using pow(), using stdio.h library only).
The question is to get the user to give you two numbers - X and N
the program will print The result of the following equation:
1+2x+3x^2+4x^3+....+nx^(n-1)
For example for the input of - X=2 N=3
1*2^0 + 2*2^1 + 3*2^2
What the program will print is "17"
This is my attempt so far, I got to the Power function but I cant find a way to incorporate into the programm itself.
#include <stdio.h>
int main(void)
{
int i, j=0, b = 0;
float x, n;
double sum = 0, sumt=0;
do{
printf("Please enter two numbers \n");
flushall;
scanf("%f %f", &n, &x);
} while (x <= 0);
for (i = 1; i <= n; i++){
sum = x*x;
}
sumt += sum;
printf("%f", sum);
}
Instead of trying to create an implementation of pow, you will need to take advantage of the relationship between the terms of the expression.
The n-th term is nx^(n-1). The n-1-the term is (n-1)x^(n-2).
If we denote the n-th term as T(n) and denote the n-1-th term as T(n-1),
T(n) = T(n-1)*x*n/(n-1)
Given the starting value of the first term,
T(1) = 1
you can compute the subsequent terms using the above formula.
The following code should work.
// Initialize the values for N=1
term = 1;
sum = 1;
// Iterate starting from 2
for (i = 2; i <= n; i++){
term *= x*i/(i-1);
sum += term;
}
The working Program based on the tips given by the almighty #R_Sahu (And others ;D)
**
#include <stdio.h>
int main(void)
{
int i, j = 0, c = 0;
float x, n, b = 0;
double term, sum;
do {
printf("Enter Two Numbers\n");
flushall;
scanf("%f%f", &n, &x);
} while (x < 0);
for (i = 2; i < n + 2; i++)
{
term = 1;
sum = 1;
for (i = 2; i <= n; i++){
term *= x*i / (i - 1);
sum += term;
}
}
printf("The answer is %.lf ", sum);
}
I will not give you the code, but the reasoning you should follow
First you have to somehow get the data from the user (as a parameter, from stdio... whatever)
x = getFromUser
n = getFromUser
You will then need to init a temporary result
result = 0
How many times do you have to add? -> Exactly n times
for(ii=0;ii<n;ii++) {
result = result + pow((ii*x),(ii-1)) //There is something missing here, I'll let you guess what
}
But wait; you cannot use pow. So you have to program it by yourself (I guess that's the idea of the exercise)
then you need a function, and it has to return an int (actually, it may return even irrational numbers, but I don't think they will require you to do that)
int customPow(int base, int exponent) {
//Put your for in here, and may the pow be with you
}
You need to figure out the code yourself, but the general idea is as follows:
Create your own pow function which returns x*n.
int pow(int x, int n){
//use a for or while loop to calculate x (*x)n times.
//pay attention to the base cases (i.e., when n = 0, or 1 etc)
}
ans = 0;
for(i = 0 to N-1){
ans = ans + pow(x,i-1)*i;
}

Issue with an early Euler problem in C - why am I getting output "nan"?

Maybe a small problem for this forum, but here goes:
The ProjectEuler.net problem #2 is as follows:
By considering the terms in the
Fibonacci sequence whose values do not
exceed four million, find the sum of
the even-valued terms.
Why am I getting "nan" output?
#include <stdio.h>
int fiblist[] = {0,1};
long double sum = 0;
void fibonacci(){
int i = 2;
while (fiblist[i] < 4000000){
fiblist[i] = fiblist[i-1] + fiblist[i-2];
i++;
}
}
void main(){
fibonacci();
int i = 0;
for (i = 0; i != '\0'; i++){
if (fiblist[i] % 2 == 0)
sum += fiblist[i];
}
printf("%Lf \n", sum);
}
while (fiblist[i] < 4000000){
At this point, you haven't actually assigned anything to fiblist[i].
(Also, unrelated, but why do you need a double, if you're only working with integers significantly smaller than 2**31?)

Resources