Approximate Pi/Taylor series; prompt user input - c

I have another problem for homework. This time I know where I am at generally, but I can see that I have some glaring issues with the code. Recently I lost my keys, and it's kind of like that. I don't know exactly WHERE I went wrong with my code, but I have a good idea, and I'd like you to help me find it.
The problem is to approximate pi using the Taylor series.
Now, my problem isn't exactly to get it to approxate so that it equals pi. Rather approximate pi using first N terms as entered by the user. So for example, if I would enter 2, then I should run through the first 2 since N=2. My problem is the way printF represents it (and a variable appears to be uninitialized). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms;
int sign= 1;
int n;
float sum= 0.0;
float next_Term;
float final_sum;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&n);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
sum= sum+next_Term;
next_Term = sign*(1.0/(2*n-1));
sign = sign*-1;
}
final_sum = sum*4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}

I don't know exactly WHERE I went wrong with my code
Firstly you are scanning value into a variable n and then later using it as an iterator variable. Change this to be num_Terms. This should solve your main problem of not considering the number of terms.
Then, it is preferable to initialize the variable before you use it, which would then get rid of the warning you get.
int main(void)
{
//program to calculate series of numbers equal to pi/4
//declare variables
int num_Terms = 0;
int sign = 1;
int n = 0;
float sum = 0;
float next_Term = 0;
float final_sum = 0;
//prompt user for input
printf("Enter a value for integer n: ");
scanf("%i",&num_Terms);
//perform calculations
for(n = 1; n<= num_Terms; n=n+1) {
//not too sure if you need to reverse this order of calculation of sum
sum = sum + next_Term;
next_Term = sign * (1.0/(2*n-1));
sign = sign * -1;
}
final_sum = sum * 4;
//display result
printf("\n 4 * %f = %f\n",sum, final_sum);
return 0;
}

Related

Trying to find the inverse of the matrix in C, but the program is not calculating correctly

There was a question that I needed to find the inverse of the matrix (actually it's about cryptography, but never mind) and to be honest the code works. Nevertheless, if you insert certain numbers into the matrix, the program just fail in to calculate it. Let me show you the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, Mtx_P[4], temp;
float D, Mtx_I[4];
printf("\nInsert the values in a matrix 2x2: "); // Insert the values
for(i=0;i<4;i++)
{
scanf("%d", &Mtx_P[i]);
}
printf(" \n");
for(i=0;i<4;i++) // Print the values
{
printf("%d\t", Mtx_P[i]);
if(i == 1)
{
printf("\n\n");
}
}
D = (Mtx_P[0] * Mtx_P[3]) - (Mtx_P[1] * Mtx_P[2]); // Find and print the determinant
printf("\n\n-------------------------\n\nDeterminant = %f\n", D);
float Mtx_Pf[4];
//double Mtx_Pf[4]; I've tried with double to see if worked
for(i=0;i<4;i++) // Find the inverse...
{
Mtx_Pf[i] = Mtx_P[i];
}
Mtx_I[0] = Mtx_Pf[0]/D; // ...divind the values by the determinat
Mtx_I[1] = Mtx_Pf[1]/D;
Mtx_I[2] = Mtx_Pf[2]/D;
Mtx_I[3] = Mtx_Pf[3]/D;
temp = Mtx_I[0]; // swaping the places of the first number with the lastest one
Mtx_I[0] = Mtx_I[3];
Mtx_I[3] = temp;
Mtx_I[1]*=-1; // the secondary diagonal get negative
Mtx_I[2]*=-1;
printf("\n-------------------------\n\nThe invertible Matrix:\n\n ");
for(i=0;i<4;i++) // Print the inverse
{
printf("%f\t", Mtx_I[i]);
if(i == 1)
{
printf("\n\n");
}
}
double test = 1/(-26);
printf("\n\n-------------------------\n(Test: %lf)\n\n", test); // Testing to see if it can't calculate
return 0;
}
My problem happens when I try to divide the element by the determinant using this matrix:
1 10
3 4
When is the time to calculate 1 by -26 (determinant) it prints 0,0000, but actually 1/(-26) is −0,038461538 (according to the calculator).
You probaly already realize that this trouble doesn't have any relation with matrixes, but somebody knows how to fix this error?
The issue is that your temp variable (used for swapping) is an int and assigning a float to an int truncates the value. Define it as a float or double instead.
float D, Mtx_I[4], temp;
In addition, note that 1/(-26) is integer division, resulting in truncation. To perform floating-point division, one of the operands must be a floating-point value (e.g. 1./-26).

C program for first seven terms in natural logarithm. I am not getting the right answer, can anyone review the following code

C program for first seven terms in natural logarithm. I am not getting the right answer, can anyone review the following code.
#include<stdio.h>
int main(){
float x,i,sum,result=0;
printf("Enter value of x:");
scanf("%f",&x);
for(i=2;i<=7;i++)
{
sum = (x - 1)/x;
result = (sum + (0.5 * pow(sum,i)));
}
printf("Sum of series of Natural Logarithm is: %0.2f",result);
return 0;
}
You haven't implemented the series correctly.
The iteration should begin at 1
The 0.5 is only correct for the second term
You overwrite result from each term instead of summing it.
Here is the corrected code. I also changed float to double, and i to int.
#include <stdio.h>
#include <math.h>
int main(void)
{
double x, sum, result = 0;
int i;
printf("Enter value of x: ");
int res = scanf("%lf", &x);
if(res != 1 || x <= 0.5) // validate
return 1;
for(i = 1; i <= 7; i++)
{
sum = (x - 1) / x;
result = result + pow(sum,i) / i;
}
printf("Sum of series of Natural Logarithm is: %f\n", result);
printf("The library function log() calculates: %f\n", log(x));
return 0;
}
Program session
Enter value of x: 0.75
Sum of series of Natural Logarithm is: -0.287697
The library function log() calculates: -0.287682

Why is the number declared in the double function not used? (C)

#include <stdio.h>
double calculate_average (int number)
{
static int numberInput = 0; //counter
static int sum = 0;
sum = sum + numberInput;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average;
while (1)
{
int number;
scanf("%d", &number);
if (number == 0)
break; //stops if number == 0
else
average = calculate_average(number);
}
printf("%.1f\n", average);
return 0;
}
As I can personally tell, the function is trying to calculate the average. But why does the main function not use the number in the calculate_average function?
As written, your calculate_average function does not use its given number argument because, nowhere in that function, do you instruct it to do so. Most likely, your sum = sum + numberInput; should really be sum = sum + number; (thus adding that given number to the running total).
A couple of other points:
You should initialize your average variable (to 0.0), otherwise you'll get a crazy result if you give your program an empty list (i.e. give zero as the first entry).
As your function returns a double, it is best to have the sum variable also as a double; otherwise, you are performing integer arithmtic in your calculation, and all returned values will be truncated to integers (losing any fractional parts).
Others will likely point out that you should always check the value returned by your scanf call (it will be 1 if the read operation succeeds) and add code to handle any error; however, addressing that point here is, IMHO, beyond the 'remit' of this question, but see this answer to How validate user input when the expected value is of type int and the entered value is not of type int?.
Here's a possible working version:
#include <stdio.h>
double calculate_average(int number)
{
static int numberInput = 0; //counter
static double sum = 0.0;
sum = sum + number;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average = 0.0; // Always best to initialize variables!
while (1) {
int getal;
scanf("%d", &getal);
if (getal == 0)
break; //stops if getal == 0
else
average = calculate_average(getal);
}
printf("%.1f\n", average);
return 0;
}
Please feel free to ask for any further explanation and/or clarification.

|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;
}

Program to reverse a number without using an array

This is the code that I used. It works perfectly, but I don't understand why it works. I just kept changing my original logic until I started using -1 in the counter loop.
#include<stdio.h>
#include<math.h>
int main(){
int number, reverse, sum =0;
scanf("%d", &number);
int temp = number;
int ctr;
for(ctr = -1; temp!=0; ctr++)
temp = temp/10;
while(number)
{
sum = sum + (number%10 * (pow(10, ctr--)));
number = number/10;
}
printf("%d", sum);
return 0;
}
same basic math but so much easier to understand:
unsigned int number = 123456789;
unsigned int reversed = 0;
do {
reversed *= 10;
reversed += number % 10;
number /= 10;
} while (number > 0);
Although this is kind of awkward to explain the logic of the code that you wrote it yourself, I understood the logic behind it.
Indeed, I was looking for a solution to solve this problem: How to reverse any positive integer without using arrays or indexed variables to which your code was the solution I was looking for.
The logic of your programme is like this:
you first count the digits of the given number in the FOR-loop in the shortest possible way. you need this because you have to 10-power each remainder up to digits of the given number in the next WHILE-loop and you store/add the result of this each time in the variable named SUM. The final result of this would be the whole integer to be reversed.
PS1:
You do not need the variable named REVERSE. Just drop it or replace SUM with it.
PS2:
You really do not need to go that long way to do this. Here's another shorter version:
#include <stdio.h>
void main (void){
unsigned short int uNum, nReversed;
puts ("Enter a positive integer number: ");
scanf ("%hu", &uNum);
while (uNum != 0){
nReversed = uNum%10 + nReversed*10 ;
uNum /= 10;
}
printf ("\n\n\nThat is %d", nReversed);
}

Resources