We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}
Related
I am creating a program that uses a while loop to provide multiple pieces of information from input given by the user. One of these pieces is the smallest number entered. I can't get it to print anything but 0. Any idea why?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num, sum = 0, sm, lg = 0, count = 0, avg = 0;
printf("Please enter a series of numbers (-1 to terminate): ");
scanf("%f", &num);
while(num > -1){
sum += num;
if(lg < num)
lg = num;
if(sm > num)
sm = num;
scanf("%f", &num);
count++;
avg = sum / count;
}
printf("The sum of your numbers is: %.4f\n", sum);
printf("You entered %.4f numbers\n", count);
printf("The average of the numbers you entered is: %.4f\n", avg);
printf("The smallest number you entered is: %.4f\n", sm);
printf("The Largest number you entered is: %.4f", lg);
return 0;
}
ex entry- 15
43
22.5
57.6
-1
Output-
sum:138.1000
4 numbers entered
average: 34.5250
smallest: 0.0000
Largest: 57.6000
In your code, sm has an undefined value because you aren't initializing it. You can initialize it to something like a very large number (or, even better, INFINITY) so it can be properly compared. The same goes for lg: if you want it to work for negative values too, you should initialize it with a very small value (-INFINITY). You can use INFINITY by including math.h.
the posted code does not compile!
first, because it is missing the needed #include statements for the needed header files. Specifically:
#include <stdio.h>
Then regarding this code block:
if(sm > num)
sm = num;
on the first pass through the while() loop, the variable sm is not initialized so accessing its' contents is undefined behavior.
Also, if using visual studio in debug mode, then all the stack is cleared to 0, so no other value will ever be assigned to it. This is why the algorithm always returns 0
Here's what I regard as a workable program. It uses double rather than float; if you insist, you can change the types and (input) formats to suit your desires. It has no particular limit on the number of rows it will accept. It doesn't output anything if there were no inputs. There is absolutely no need to use an array for the calculations. It uses use +∞ and -∞ to initialize the smallest (min) and largest (max) values respectively. Even if the only input is +∞ or -∞ (spelled +Inf or -Inf, or +Infinity or -Infinity, optionally without the + sign, and with upper-case, lower-case or mixed-case spelling) the correct values are produced.
#include <stdio.h>
#include <math.h>
int main(void)
{
double min = +INFINITY;
double max = -INFINITY;
double sum = 0.0;
size_t cnt = 0;
double value;
while (scanf("%lf", &value) == 1)
{
sum += value;
cnt++;
if (value > max)
max = value;
if (value < min)
min = value;
}
if (cnt > 0)
{
printf("Count = %zu\n", cnt);
printf("Sum = %g\n", sum);
printf("Min = %g\n", min);
printf("Max = %g\n", max);
printf("Average = %g\n", sum / cnt);
}
return 0;
}
Given ten random values between -1E6 and +1E6:
989375.672
-826955.668
224850.463
-401605.702
-45457.787
259618.099
821069.496
-268408.724
-512449.113
-46404.246
the program produces the output:
Count = 10
Sum = 193632
Min = -826956
Max = 989376
Average = 19363.2
I should probably put a bit more control on the output formatting, but the %g option is quite useful for numbers with wide ranges. Given the input data, using %11.3f would work well (it was used to format the output from the random number generator I used).
I apologize if this appears as homework, but I am struggling to understand recursion in C.
Im trying to solve a problem where I must determine the cumulative product of n floating-point numbers, and I must read in a new number into the computer during each call of the recursive function. (Problem 7.49d of Schaums Outline of Theory and Problems of Programming with C)
I interpreted this to mean, each time the recursive function is called, the user has to enter a new value, and this value is multiplied with the previous value.
p = (f1 * f2 * f3 * ... * ft)
I finally was able cobble this solution together:
`
#include <stdio.h>
float product(int n); /* function prototype */
int main()
{
printf("This program returns the culmulative product of\n"
"each number entered into the computer.\n");
int n;
printf("Enter how many numbers (n): ");
scanf("%d", &n);
printf("culmulative product >> %2.2f", product(n));
printf("\n");
return 0;
}
float product(int n)
/* this function multiplies each number entered, recursively. */
{
float sum = 1.0; float number;
if(n > 0)
{
printf("number = ");
scanf(" %f", &number);
sum = sum * number;
printf("sum > %f\n", sum);
number = product(n - 1);
return(sum * number);
}
}`
But I am still struggling to understand what is happening in each recursive step, and why I had to number = product(n - 1) and return (sum * number);
Can someone please help explain it to me?
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
I am trying to use "Press 'q' to quit" functionality to exit a do...while loop for calculating the average of a series of user-defined integers. Following several examples I was able to get the exit value to work but it is being included as part of calculating the average.
Example:
quixote#willow:~$ gcc sentinel-borked.c -o sentinel-borked
sentinel-borked.c: In function 'main':
sentinel-borked.c:22:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
sum = sum + value;
^
quixote#willow:~$ ./sentinel-borked
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: 1
Enter an answer string or q to quit: q
Count is: 3
Average is: 214197589.333333
quixote#willow:~$
I know that the "q" is being treated as an integer, but I'm not sure how to re-write my code to escape it. :(
The simplest workaround that I can think of is to prompt the user for an end point (i.e. "how many integers are you averaging?") and use that, but I would really like to figure this out.
Here is the code I have so far.
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg;
char *value;
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
do {
// Loop through to input values
printf("\nEnter an answer string or q to quit: ");
fgets(value, 10, stdin);
if (value >= 0){
sum = sum + value;
count = count + 1;
}
else {
printf("\nValue must be positive");
}
} while (value[0] != 'q');
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
return 0;
}
EDIT: Replaced screenshot with plain-text inside of a code block. Original image still located at: https://i.stack.imgur.com/qza1N.png
Try this:
#include <stdio.h>
#include <string.h>
int main ()
{
/* variable definition: */
int count, sum;
double avg=0;
char value[10]="";//make value an array or allocate memory for it using malloc and also null initiate it
/* Initialize */
count = 0;
sum = 0;
avg = 0.0;
fgets(value,10,stdin);
if(value[strlen(value)-1]=='\n'){//if the user enters a string less than 10 chars a newline will also be stored inside the value array
value[strlen(value)-1]='\0';//you need to remove that \n and replace it with null
}
else{
while((getchar())!='\n');//just removing any extra chars left(when the user enters a string greater than 10 chars)
}
while(value[0]!='q'){//beware it will only check for the first char of the array to be q, anything else will still proceed the loop
sum+=strtol(value,NULL,10);//use this to convert integers inside the array to long ints(many other ways exists)
count++;
fgets(value,10,stdin);//overwrite value each time to get input
if(value[strlen(value)-1]=='\n'){
value[strlen(value)-1]='\0';
}
else{
while((getchar())!='\n');
}
}
// Calculate avg. Need to type cast since two integers will yield an integer
printf("\nCount is: %d", count);
if(count==0){
printf("\nAverage is: %lf\n", avg);
}
else{
avg = (double) sum/count;
printf("\nAverage is: %lf\n", avg);
}
return 0;
}