do-while function not returning value - c

#include <stdio.h>
#include <cs50.h>
int counter(int n,int x, int y);
int main (void){
//prompt for start and end year;
int start;
do{
start = get_int("starting population no: ");
}
while( start < 9);
int end;
do {
end = get_int("ending population no: ");
}
while (end < start);
// calculate number of years until we reach threshold
int years = 0;
counter(years, start, end);
}
int counter(int n, int x, int y){
do {
x = x + x / 3 - x / 4;
n++;
}
while(x < y);
return n;
printf("years: %i", n);
}
below function counter is supposed to return the value that'll our year. but its in not returning that value idk what is not working and if my while condition is working well cuz it is not returning anything. pls tell where im wrong.

It is returning a value, but you do nothing with it.
counter(years, start, end);
Should be
int n = counter(years, start, end);
printf("years: %i", n);
You do have a statement that attempts to print the value, but it's not reachable since it's after a return. Always enable your compiler's warnings. It would have caught this error. (With gcc, I use -Wall -Wextra -pedantic -Werror.)

You probably want something like this:
...
// calculate number of years until we reach threshold
int years = counter(0, start, end);
printf("years: %i", years);
}
int counter(int n, int x, int y){
do {
x = x + x / 3 - x / 4;
n++;
}
while(x < y);
return n;
// don't printf n here, it's pointless
}
There may be more errors elsewhere, I didn't check.

Related

find prime numbers including and between two numbers using

I need to find prime numbers between and including two numbers, using functions.
For example, with <<(3 23)>> the output is 3 5 7 11 13 17 19 23
This is my code so far, but I’m having troubles with it. What am I doing wrong or how can I improve my solution?
#include<stdio.h>
int check_prime(int l,int u){
int x, i;
for (x = l; x <= u; x++){
for (i = 2; i < x; i++){
if (x % i == 0) break;
}
}
if (i == x) return x;
}
int main(){
int x, y, f;
scanf("%d%d", &x, &y);
f = check_prime(x, y);
printf("%d", f);
return 0;
}
You are printing the value returned from check_prime() and that will be one value only. If you want to print all the prime numbers in a range, i suggest instead of returning value from check_prime() you print the value in that function.
#include<stdio.h>
void check_prime(int l,int u){
int x,i;
for(x=l;x<=u;x++){
for(i=2;i<x;i++){
if(x%i==0)
break;
}
if(i==x){
printf("%d ", x);
}
}
}
int main(){
int x,y;
scanf("%d%d",&x,&y);
check_prime(x,y);
return 0;
}
Here is the executable code: https://repl.it/#fiveelements/PrintPrimeNumbersInARange?language=c

Calculate power of all the numbers till n-1

Given n, the program should calculate 1^1 + 2^2 + 3^3 + ... till n-1^n-1. Below is my code, in which there is one function inside while loop which and the passed value is from n-1 in the function. The function definition has two variables which return the ans. Output is wrong always 1.
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
int la, ans;
if(y==0)
return 1;
else
la= (x*power(x, y-1));
ans+=la;
return ans;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, a, b, res, res1;
scanf("%d%d", &n, &m);
while(n-- && n>0)
{
a = power(n-1, n-1);
}
printf("%d", a);
}
return 0;
}
Some problems in your code.
As pointed in another answer, your power function was broken:
ans was not initialized
{ } were missing after the else
in the while, you compute x^x, but you forget the result, whearas you
should sum it.
first thing you do in while loop is to decrease n and to compute power(n-1, n-1)
that sound not logical.
Hence, your corrected code could be:
#include <stdio.h>
#include <stdlib.h>
int power(int x, int y)
{
if(y==0)
return 1;
else
return x*power(x, y-1);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, b, a = 0;
scanf("%d%d", &n, &m);
while(n>1)
{
--n;
b = power(n, n);
a += b;
printf("%d^%d -> %3d\n",n, n, b);
}
printf("sum= %d", a);
}
return 0;
}
Gives for n = 6:
5^5 -> 3125
4^4 -> 256
3^3 -> 27
2^2 -> 4
1^1 -> 1
sum=3413
C uses braces to form blocks, your power() function looks like it's wanting to use indentation like in Python.
It should probably be:
int power(int x, int y)
{
int la, ans;
if(y==0)
return 1;
else
{
la= (x*power(x, y-1));
ans+=la;
return ans;
}
}
Of course since the first if has a return, the else is pointless, and you can simplify the code:
int power(int x, int y)
{
if (y==0)
return 1;
return x * power(x, y-1);
}
The variable ans was never assigned to, that looked broken so I simplified it out.
Of course this is susceptible to integer overflow.

How to print this series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) in C/C++?

I wish to write a program which calculates the series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) by taking x and n as user inputs.
This is what i've tried, and well there's no output when I enter the values for x,n:
#include<stdio.h>
#include<math.h>
//#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
double x,n,res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%lf%lf",&x,&n);
/*if(n%2!=0)
{
printf("Please enter a positive value!\n");
exit(0);
}*/
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n %lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r,fact,exec;
for(i=1;i<=t;i+2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1.0;
while(p>0)
{
f*=p;
p--;
}
return f;
}
When I enter values for x and n, it simply shows nothing.
While I've written in C, C++ solutions are also appreciated.
Output window in code::blocks
The loop
for(i=1;i<=t;i+2)
in the function series() is an infinite loop when t >= 1 because i isn't updated in the loop. Try changing + to += and use
for(i=1;i<=t;i+=2)
instead. Also it seems you should use type int for x and n in the function main() because the arguments of series() is int. Don't forget to change the format specifier when changing their types.
Thanks to all those who helped. Here's the final working code:
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
int x,n; double res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%d%d",&x,&n);
if(n%2==0)
{
n=n-1;
}
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n%lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r=0.0,fact,exec;
for(i=1;i<=t;i+=2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1;
while(p>0)
{
f*=p;
p--;
}
return f;
}
in loop we step by two for getting odd numbers.by multiplying the current temp variable by the previous temp variable in the loop with neccesary terms like x square and dividing by i*(i-1) i.e for factorial and multiply with -1 i.e to achive negavtive number alternatively. by using this temp variable and adding it to sum variable in every iteration will give us answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, x;
cout << "enter x and no.of terms: ";
cin >> x >> n;
float sum = 0, temp = x;
for (int i = 3; i < 2 * n + 2; i = i + 2)
{
temp = ((-1 * temp) *(x*x)) / i*(i-1);
sum = sum + temp;
}
cout << x + sum;
return 0;
}
// series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)
#include<stdio.h>
#include<math.h>
double factorial (int);
double calc (float, float);
int
main ()
{
int x, deg;
double fin;
printf ("x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf ("Enter value of x\n");
scanf ("%d", &x);
printf ("highest degree in denom i.e., 1 or 3 or 5 whatever, it should be odd .\n");
scanf ("%d", &deg);
fin = calc (x, deg);
printf ("the summation of series =%1f\n", fin);
return 0;
}
double calc (float num, float res)
{
int count, sign = 1;
double rres = 0;
for (count = 1; count <= res; count += 2)
{
rres += sign * (pow (num, count) / factorial (count));
sign *= -1;
}
return (rres);
}
double factorial (int num)
{
int count;
double sum = 1;
for (count = 1; count <= num; count++)
{
sum *= count;
}
return (sum);
}

C functions in finding a max value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How to write a C Function that takes three integers as arguments and returns the value of the largest one.
int largest(int x,int y,int z)
{
int val1,val2,val3;
int maximum;
printf("enter value \n");
scanf("%d",&val1,&val2,&val3);
maximum=largest(val1,val2,val3);
printf("the largest integer is %d = \n",maximum);
return 0;
}
int largest(int x,int y,int z)
{
if(x>=y && x>=z)
printf("Largest number = %d", x);
if(y>=x && y>=z)
printf("Largest number = %d", y);
if(z>=x && z>=y)
printf("Largest number = %d", z);
}
I have tried this codes but they don't work i need help please I am also a beginner at this
This should work fine.
int val1,val2,val3;
int maximum;
printf("enter value \n");
scanf("%d %d %d",&val1,&val2,&val3);
maximum=largest(val1,val2,val3);
printf("the largest integer is %d = \n",maximum);
return 0;
}
int largest(int x,int y,int z){
int max;
max=x;
if(y>max){
max=y;
}
if(z>max){
max=z;
}
return max;
}
Try this one:
#include <stdio.h>
int largest(int x, int y, int z);
int main() {
int val1, val2, val3;
int maximum;
printf("enter value \n");
scanf("%d", &val1, &val2, &val3);
maximum = largest(val1, val2, val3);
printf("the largest integer is %d = \n", maximum);
return 0;
}
int largest(int x, int y, int z){
if (x >= y && x >= z)
return x;
if (y >= x && y >= z)
return y;
// otherwise
return z;
}
The problem is that you wanted the method to return the largest value, but simply didnt do that - the code is not compiling because the largest function is defined to "return" an int but there's no return statement anywhere in your function.
If you dont know what exactly "returning function" is then take a look at this tutorial: http://www.cplusplus.com/doc/tutorial/functions/
This is a pretty short way of doing what you want:
int largest(int a, int b, int c)
{
a = (a > b) ? a : b;
a = (a > c) ? a : c;
return a;
}
To return a value you must use a return statement in function.
Let us inspect what you've done,
#include<stdio.h>
int largest(int x,int y,int z)/* missed ';' */
/* missed 'void main()' */
{
int val1,val2,val3;
int maximum;
printf("enter value \n");
scanf("%d",&val1,&val2,&val3); /* missed format specifier for other two values */
maximum=largest(val1,val2,val3);
printf("the largest integer is %d = \n",maximum);
return 0;
}
int largest(int x,int y,int z)
{
if(x>=y && x>=z)
printf("Largest number = %d", x);/* written print statement instead of return statement */
if(y>=x && y>=z)
printf("Largest number = %d", y);/* written print statement instead of return statement */
if(z>=x && z>=y)
printf("Largest number = %d", z);/* written print statement instead of return statement */
}
After modification the code should be like this,
#include<stdio.h>
int largest(int x,int y,int z);
int main()
{
int val1,val2,val3;
int maximum;
printf("enter value \n");
scanf("%d %d %d",&val1,&val2,&val3);
maximum=largest(val1,val2,val3);
printf("the largest integer is %d \n",maximum);
return 0;
}
int largest(int x,int y,int z)
{
if(x>=y && x>=z)
return x;
if(y>=x && y>=z)
return y;
if(z>=x && z>=y)
return z;
}

Custom Recursive function |returning no values at all| in C

I thought of making this An=8(An-1)*(An-1)/An-2 while a1=1,a0=1
With the following code for n=2 a2=0.0000 which is altogether wrong
On the other hand (Sum of An) S(n)=1+1+0.0000(false number) theoretically correct
#include <stdio.h>
float rec(int n);
float sum(int n);
main()
{
int n;
printf("\nInput N of term an: ");
scanf("%d",&n);
printf("\n\na%d=%f",n,rec(n));
printf("\n\nS(%d)=%f",n,sum(n));
}
float rec(int n)
{
int i;
float a[1000]={1,1};//a0=1,a1=1
if(n<0)
printf("\nNegative values of N are invalid");
else if(n==0)
return a[0];
else if(n==1)
return a[1];
else if(n>1)
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
}
float sum(int n)
{
int i;
float sum=0;
for(i=0;i<=n;i++)
sum+=rec(i);
return sum;
}
float a[1000]={1,1};
initializes a[0] = 1 and a[1] = 1 and rest of the elements to 0.
Now, you are returning a[i] from your function. For n=2 it will return a[3], which is 0 of course, but not the a[2] as you are expecting.
Now just change the return value to a[i-1] and it will work.
float rec(int n)
{
int i;
...
...
return a[i-1];
}
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
problem here, you will always get zero!!! why?
say i input 3,, now say i = 3,alls well a[3] gets calcualted, now you program goes back to the for loop, now i =4, it now does not fit the check i<=n, and so now i is 4,
you are returning a[i] which is actually a[myanswer+1]...
fix it by returning a[i-1]
At this point in rec:
return a[i];
i is 3, not 2, because it was incremented before the last test of the loop. As such you're returning the element of the array after the last one set. Be careful if you fix this by returning a[i-1] because if i is never initialized or is 0, this will cause a problem. You should clean up the rec method a bit to handle these corner cases, but the immediate problem is that i is 3, not 2.
Replace
return a[i];
with
return a[n];
(As an aside, you do not need the extra branches for 0 and 1.)
A beautiful example of Schlemiel the Painter's algorithm :)
About half the computations are done unnecessarily multiple times
The array is unnecessary and defeats the whole point of using a recursive approach
Beside, it is defined to hold 1000 values, but the function grows so fast that it will exceed a float capacity after 10 terms or so.
A more streamlined version here :
#include <stdio.h>
float A (int n, float * sum)
{
if (n <= 0) { *sum = 0; return 0; }
if (n == 1) { *sum = 1; return 1; }
if (n == 2) { *sum = 2; return 1; }
float anm2 = A(n-2, sum); // store A(n-2). sum will be overwritten by A(n-1)
float anm1 = A(n-1, sum); // store A(n-1) once to avoid calling A twice, and get preceding sum
float an = ((8 * anm1*anm1) - 1)/anm2;
*sum += an;
printf ("index %d : term %g sum %g\n", n, an, *sum);
return an;
}
int main (void)
{
int n;
float sum;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
printf("\na%d=%f",n,A(n, &sum));
printf("\n\nS(%d)=%f",n,sum);
}
Beside, recursion is unnecessary and leads to inefficient and confusing code.
See a more straightforward solution here:
#include <stdio.h>
typedef struct {
float term;
float sum;
} A; // current term and sum of series A
void compute_A (int n, A * res)
{
int i;
float anm1, // a[n-1]
anm2; // a[n-2]
// special case for n<=1
if (n == 1)
{
res->sum = res->term = 1;
return;
}
if (n <= 0)
{
res->sum = res->term = 0;
return;
}
// initial terms
anm2 = anm1 = 1;
// initial sum
float sum = anm1+anm2;
// compute the remaining n-2 terms and cumulate the sum
for (i = 2 ; i <= n ; i++)
{
// curent term
float an = ((8 * anm1*anm1) - 1)/anm2;
// cumulate sum
sum += an;
// shift computation window
anm2 = anm1;
anm1 = an;
printf ("index %d : term %g sum %g\n", i, an, sum);
}
// report result
res->sum = sum;
res->term = anm1;
}
int main (void)
{
int n;
A res;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
compute_A (n, &res);
printf("\na%d=%f",n,res.term);
printf("\n\nS(%d)=%f",n,res.sum);
}
float rec(int n){
static max_i = 1;
static float a[1000]={1,1};//a0=1,a1=1
int i;
if(n<0){
printf("\nNegative values of N are invalid");
return NAN;//<math.h>
}
if(n >= 1000){
printf("\nMore than 1000 are invalid");
return NAN;
}
if(n<2)
return a[n];
if(n>max_i){
for(i=max_i+1;i<=n;++i)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
max_i = n;
return a[n];
}
return a[n];
}

Resources