Integration by Simpson's Rule - c

One of my assignments was to create a c program that uses the Simpson's 1/3 rule to find the sum. I am running into issues that I am having trouble fixing. Can some one with more experience point me in the right direction?
In theory my code integrates y=ax^2+bx+c where the user selects values for a,b,c and then the user selects the upper and lower bounds [d,e]. Then the user selects the n value which splits up the area into more rectangles (the value that we will use in my class is 100, so the area is split into 100 rectangles). After which it runs through the Simpson's rule and prints out the sum.
//n is required number of iterations.
#include<stdio.h>
#include<conio.h>
#include<math.h>
double integral (int a,int b,int c,int d,int e,int n)
int main()
{
double a, b, c, d, e, n;
printf("Please select values for y=ax^2+bx+c");
printf("Please select value for a");
scanf("%d", &a);
printf("Please select value for b");
scanf("%d", &b);
printf("Please select value for c");
scanf("%d", &c);
printf("Please select value for the upper limit");
scanf("%d", &d);
printf("Please select value for the lower limit");
scanf("%d", &e);
printf("Please select the number of rectangles for the Simpson's Rule (Input 100)");
scanf("%n", &n);
int i;
double sum=0,length=(double)(d-e)/(n),ad,bd,cd,dd;
ad=(double)a;
bd=(double)b;
cd=(double)c;
dd=(double)d;
for (i=0;i<n;i++)
{
sum+=(ad*(dd*dd+2*dd*length*i+length*length*i*i)+bd*(dd+length*i)+cd)*length;
printf("the value is = %d",sum);
}
return sum;
}

Why do you think this
scanf("%e", &e);
should be that way?
The scanf() function takes a format specifier to match the scanned input with, in your case you want to store the values in a double variable, for which you need the "%lf" specifier, so all your scanf()'s should change to
scanf("%lf", &whateverDoubleVariableYouWantToStoreTheResultIn);
You don't need to cast from a variable of a given type to the same type, like here
dd=(double)d;
And also, you must know, that scanf() returns a value, you should not ignore it because your program will misbehave in case of bad input, you should check scanf() in a library manual or the C standard to understand better how to use it.

In addition to #iharob fine advice:
Change n type
// double a, b, c, d, e, n;
double a, b, c, d, e;
int n;
Adjust input code
// and previous lines
if (1 != scanf("%lf", &e)) // %d --> %lf
Handle_InputError();
printf("Please select the number of rectangles for the Simpson's ...
if (1 != scanf("%d", &n) // %n --> %d
Handle_InputError();
Adjust output
// printf("the value is = %d",sum);
printf("the value is = %e",sum); // or %f
Minor bits
// int main()
int main(void) // or int main(int argc, char *argv[])
// return sum; returning a double here is odd
return 0;

Related

Program stops when inputing a variable

This is literally my first lines of code in C, so it's really basic.
The code is this:
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", l);
printf("Enter the breadth of the rectangle");
scanf("%d", b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}
It starts running properly, outputs "Enter the length of the rectangle", but when I input a number, it just stops and I don't get to input the second value.
What am I missing?
You have to pass pointers to the variables to get the values instead of the values in the variables.
You should use unary & operators to get pointers like this:
scanf("%d", &l);
Note that you don't need & to read strings because arrays are automatically converted to pointers to the first element (except for some cases, including when used as an operand of unary & operator).
char str[10];
scanf("%9s", str);
Corrected code
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", &l);
printf("Enter the breadth of the rectangle");
scanf("%d", &b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}

How to call a local variable from another function c

I am new to programming. I would like to call from functions(first, second, third the variables in function "enter" and in function "math" accordingly).
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void math (void);
void first (void);
void second (void);
void third (void);
void enter(void);
void scan(void);
int main()
{
first(); //function
second(); //function
third(); //function
enter(); //function
printf("\n\n Would you like to edit? (Y/N)\n\n");
scan(); //function
return(0);
}
Here is the user input:
void first (void){
float a;
printf("Enter First number: ");
scanf("%f",&a);
}
void second (void){
float b;
printf("Enter Second number: ");
scanf("%f",&b);
}
void third (void){
float c;
printf("Enter Third number: ");
scanf("%f", &c );
}
How can I call the variables from the user input to the function below?
void enter(){
float a,b,c;
printf("you have entered a: %f, b: %f, c:%f", a,b,c);
}
This is the loop in case the user would like to edit or continue with the initial input numbers.
void scan(void){
int ch;
scanf("%d", &ch);
if (ch==1){
main();
}else{
math();
}
}
Here I would also like to call the input variables from function (first, second third) in order to perform some math calculations.
void math (void){
float a,b,c;
float x,y,z;
x=a+b+c;
y= powf(x,2);
z=sqrt(y);
printf("Final Result of Addition is: %f \n Final Result of
Multiplication is: %f \n Final Result of squareroot is:%f\n
",x,y,z);
}
It's best if functions don't depend or modify data external to them. It's not always possible but it is better if they can be defined with that goal in mind.
In your case, the functions first, second, and third are doing essentially the same thing. It will be better to use just one function and give it a more appropriate name, such as read_float and change the return type so that the value input by the user is returned to the calling function.
Declare it as:
float read_float(char const* prompt);
Then, you can use it as:
float a = read_float("Enter the first number:");
float b = read_float("Enter the second number:");
float c = read_float("Enter the third number:");
etc.
The function enter does not correctly convey what it is doing. It should be renamed to something more appropriate, such as display_input_values. It can accept the values input by the user as its arguments.
Declare it as:
void display_input_values(float a, float b, float c);
and use it as:
float a = read_float("Enter the first number:");
float b = read_float("Enter the second number:");
float c = read_float("Enter the third number:");
display_input_values(a, b, c);
The scan function does not convey its meaning clearly either. You could divide scan to two functions -- one that returns you the option of whether to continue with the next inputs or to call a function that computes something with the user input.
You can get the option from the user by using a function named read_int function as:
int option = read_int("Enter 1 for next round of inputs and 2 to compute with current input:");
and use that returned value as:
if ( option == 2 )
{
// Do the computations
}
You also need another option to exit the program. The call to get the option needs to be:
char const* prompt = "Enter 1 for next round of inputs.\n"
"Enter 2 to compute with current input.\n"
"Enter 3 to exit program.\n";
int option = read_int(prompt);
Always add code to check whether scanf succeeded before proceeding to use the data that you were expecting to read into.
Here's an updated version of your code.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float read_float(char const* prompt);
int read_int(char const* prompt);
void display_input_values(float a, float b, float c);
void math(float a, float b, float c);
int main()
{
while ( 1 )
{
float a = read_float("Enter first number: ");
float b = read_float("Enter second number: ");
float c = read_float("Enter third number: ");
display_input_values(a, b, c);
char const* prompt = "Enter 1 for next round of inputs.\n"
"Enter 2 to compute with current input.\n"
"Enter 3 to exit program.\n";
int option = read_int(prompt);
if ( option == 3 )
{
break;
}
else if ( option == 2 )
{
math(a, b, c);
}
}
}
float read_float(char const* prompt)
{
float num;
printf("%s", prompt);
// For flushing the output of printf before scanf.
fflush(stdout);
if (scanf("%f", &num ) != 1)
{
print("Unable to read number. Exiting.\n");
exit(1);
}
return num;
}
int read_int(char const* prompt)
{
int num;
printf("%s", prompt);
// For flushing the output of printf before scanf.
fflush(stdout);
if (scanf("%d", &num ) != 1)
{
print("Unable to read number. Exiting.\n");
exit(1);
}
return num;
}
void display_input_values(float a, float b, float c)
{
printf("You have entered a: %f, b: %f, c:%f\n", a, b, c);
}
void math(float a, float b, float c)
{
// Do whatever makes sense to you.
}
For example declare float a,b,c; in your Main and change your functions to return a float
float first() { ... }
Then writea = first();
Local variables (as name suggests) are local and can't keep their values after function ends. You have two options:
Make functions first, second and third return their numbers and another functions get them as arguments.
Make a,b,c global variables.
The second one is much easier, but it's so called bad programming style.

Scan multiple variables depending on test cases?

I want to calculate sum of arithmetic progression in which we have to take 3 variables from user. a=first number, b= step size/increment, c=length of sequence.
If there are more than 1 test case , say three, then I have to scan a,b,c three time. How to do this?
E.g scanf (" %d %d %d", a,b,c); 3 times without affect initial values in first test case.
If you know no of test cases read it first and store it in a variable.
int calculate_ap(int a, int b, int c)
{
//Implement function to calculate Arithmetic progression and return the result
}
int main()
{
int test_cases = 0;
int a, b, c;
scanf("%d", &test_cases); //Reads no of test cases
while(test_cases--)
{
scanf("%d, %d, %d", &a, &b, &c); //read A, B, C
printf("%d\n", calculate_ap(a, b, c));
}
}
Hope this helps.

What is type mismatch redeclaration of function in c?

This is my code for simple interest using functions:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a,c;
float b,d;
printf("Enter principle value :");
scanf("%d", &a);
printf("Enter rate :");
scanf("%f", &b);
printf("Enter time:");
scanf("%d", &c);
d=si(a,c,b);
printf("The simple interest is %f", d);
getch();
}
float si(int a, int c, float b)
{
float f;
f=(p*t*r/100);
return(0);
}
So this is giving a "type mismatch redeclaration of si" as an error from float si.
First of all, this snippet
printf("Enter time:");
scanf("%d", &t);
shouldn't work as you haven't declared t as an integer, so just declare t on the line above like such.
int a, c, t;
You also didn't declare any of the variables in your si function. When you pass the c variable, it never gets initialized.
What will help your type mismatch error is a forward declaration of the si function.
By adding the line float si(int a, int c, float b); to the top of your program (above main), you let the compiler know what type of function si is, as well as what arguments to expect.
Here is my best attempt to fix up the code:
#include <stdio.h>
#include <conio.h>
float si(int a, int c, float b);
float si(int a, int c, float b){
float f;
f=(a*b*c/100);
return f;
}
void main(){
int a, c;
float b, d;
printf("Enter principle value :");
scanf("%d", &a);
printf("Enter rate :");
scanf("%f", &b);
printf("Enter time:");
scanf("%d", &c);
d = si(a,c,b);
printf("The simple interest is %f", d);
}
When you call
d = si(a,c,b);
your program doesn't know of that function, because it's defined afterwards at the bottom. Look up "forward declaration" to fix this. Also, you use the variable 't' but I can't see it defined.

C program is not adding correctly when looping over an array

I was trying to find the sum of 5 numbers (in C Language) using tutorials from "thenewboston" on Youtube. My code is:
int main(int argc, char *argv[]) {
int a, b, c, d, e;
int array[5]={a, b, c, d, e};
int sum=0;
int i;
int j;
printf("Enter your 5 numbers: ");
scanf("%d, %d, %d, %d, %d", &a, &b, &c, &d, &e);
for (i = 0; i < 5; i++){
sum+=array[i];
}
printf("The sum of 5 numbers is:%d",sum);
return 0;
}
But the weird thing was, no matter what 5 numbers I entered, I always got the sum as 48.
Either discard variables a, b, c, d, e and the array remains or vice versa
Remove variables on your first printf:
print("Enter 5 numbers: ");
Don't put variables when you did't use them.
When you put scanf as scanf("%d, %d", &var1, &var2);, you must also input the same format as
Enter 5 numbers: 10, 20
Working example(more efficient with array):
int main() {
int input[5];
int sum;
printf("Enter 5 numbers: ");
scanf("%d, %d, %d, %d, %d", &input[0], &input[1], &input[2], &input[3], &input[4]);
int i;
for (i = 0; i < 5; i++) {
sum += input[i];
}
printf("The sum is %d", sum);
return 0;
}
You aren't storing a, b, c, d, or e into the array array. You need to store them in the array after you read them in.
Your declaration of array doesn't create an array of pointers to your variables - it creates a single pointer to a contiguous block of five integer fields. You can't update those array fields by just using the addresses of a, etc., since your array doesn't point to them.
The most obvious, clear, and simple way to store them in the array (which I recommend) is:
array[0]=a;
array[1]=b;
array[2]=c;
array[3]=d;
array[4]=e;
Do this just before the beginning of your for loop.

Resources