How to call a local variable from another function c - 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.

Related

Error "too few arguments to function call, at least argument 'format' must be specified" C programming

#include <cs50.h>
//declare functions
int add_two_ints(int a, int b);
int main(void)
{
//ask the user for input
printf("give an integer: ");
int x = get_int();
printf("give me another integer: ");
int y = get_int();
//call function
int z = add_two_ints(x, y);
printf("the result of %i plus %i is %i!\n", x, y, z);
}
//function
int add_two_ints(int a, int b)
{
int sum = a + b;
return sum;
}
when i run the program i get the error too few arguments to function call, at least argument format must be specified
this is a simple function with only two arguments being pass since im new to c programming im trying to figure out where i made the mistake.
whats is the correct way to write function ?
The get_int function included as part of CS50 expects a string for a prompt, which you're not passing. So instead of this:
printf("give an integer: ");
int x = get_int();
You want this:
int x = get_int("give an integer: ");
And similarly for reading y.
I just realize what I was doing wrong the get_int was expecting a string so I just deleted the printf statement and put in on to the get_int so now when it runs it works
#include <stdio.h>
#include <cs50.h>
//declare functions
int add_two_ints(int a, int b);
int main(void)
{
//ask the user for input
int x = get_int("give an integer: ");
int y = get_int("give an integer: ");
int z = add_two_ints(x, y);
printf("the result of %i plus %i is %i!\n", x, y, z);
}
int add_two_ints(int a, int b)
{
int sum = a + b;
return sum;
}

I keep getting the message loadParameters.exe has triggered a breakpoint?

This is my assignment I am supposed to do however whenever I run my code I get the error stated in my question.
Create a function,
return type: char
parameters: int *, int *
Inside the function, ask for two integers. Set the user responses to the int * parameters.
Prompt the user for a character.
Get their response as a single character and return that from the function.
In main:
Define two variables and call your function.
Print the result of your function and the values of your variables.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
char load(int *x, int *y);
void main()
{
int integer1 = 0;
int integer2 = 0;
int *pointer1;
int *pointer2;
pointer1 = &integer1;
pointer2 = &integer2;
char returnValue;
returnValue = load(*pointer1, *pointer2);
printf("%c", returnValue);
system("pause");
}
char load(int *x, int *y)
{
char input;
printf("Please enter two integers: ");
scanf_s("%d %d", x, y);
printf("Please enter a character:");
scanf_s(" %c", &input);
return input;
}

Integration by Simpson's Rule

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;

How do you return a value from a called function to the main?

I use the return command then try to print the value from the main. It returns a value of zero (0).
This program is about temperature conversion from Celsius to Fahrenheit.
Also how can you use a rounding function to round the answer to an integer so it is not a floating point number with decimals.
#include <stdio.h>
int Cel_To_Fah(int a, int b); // function declaration
int main (void)
{
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
Cel_To_Fah(a,b); // function call
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(a,b)
{
b=1.8*a+32;
return b;
} // Cel_To_Fah
You just have to use the assignment operator:
b = Cel_To_Fah(a);
Your program has a lot of problems, though, including your Cel_To_Fah function not having a correct signature. You probably want something like:
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
You should probably get a good beginner C book.
No need of second argument to function(b).
You can do this by...
#include<stdio.h>
int Cel_To_Fah(int a); // function declaration, as it returns a values;
int main (void)
{
int a; int b;
printf(" Enter temperatrure: ");
scanf("%d", &a);
b = Cel_To_Fah(a); /* the returned value is stored into b, and as b is an integer so it is automatically rounded. no fraction point value can be stored into an integer*/
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
there are several issues. First you need to use float, not int, so that you can have values with a decimal point. otherwise your calculations will come out wrong. Also use 32.0 instead of 32 for the same reason.
Second, you need to understand that the a and b in your function are NOT the same as the a and b in main. They have the same name but are not in the same "scope". So changing the one in your function doesn't affect the one in main. That's why in main you have to say b=Cel... so that b in main will get the returned value.
finally, in c, you're supposed to put your functions above/before main. Otherwise it's technically not defined "yet", though some modern compilers will fix that for you. Read about function prototypes.
Since your function Cel_To_Fah(a,b); is returning a value (int type), you must have to assign it to a variable of its return type (int type).
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b = Cel_To_Fah(a); // function call
printf("The temperature is: %d\n", b);
and your function should be
int Cel_To_Fah(a)
{
int b = 1.8*a+32;
return b;
} // Cel_To_Fah
And do not forget to change your function prototype to
int Cel_To_Fah(int a);
I saw two issues in your code. Firstly, it is variable type. I assume that you want Celsius as integer; but Fahrenheit = 1.8*Celsius+32 should be float. Therefore b should be float.
Secondly, you should not return a value from a function via its input parameters (unless you learn pointer or call by ref). I rewrite your code as following:
include<stdio.h>
float Cel_To_Fah(int a); // function declaration
int main (void)
{
int a;
float b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b=Cel_To_Fah(a); // function call
printf("The temperature is: %.2f\n", b); //showing 2 decimal places
return 0;
} // main
float Cel_To_Fah(int a)
{
float b;
b=1.8*(float)a+32; //cast a from int to float
return b;
} // Cel_To_Fah

c program to swap values printing wrong result [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Hi I have written a c program that reads in 2 values then swaps them and prints the new values except the second value keeps showing 0. For example it you enter 10 for 'a' and 8 tor 'b', then a will be 8 but b will be 0. Does anyone know the solution to fix this? Here is the code:
#include <stdio.h>
int getData()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
int a, b = getData();
swapValues(a, b);
return(0);
}
return (a, b);
doesn't do what you think it does, it's a misapplication of the comma operator.
The expression op1, op2 evaluates both op1 and op2 but gives you the value of op2. So it's not passing back a couple of values (although some languages like Python can do this sort of thing).
Similarly,
int a, b = getData();
won't grab the mythical two values returned from getData(). Rather it will set a to an indeterminate value and set b based on the single value returned from the function.
I would be looking at something like this:
#include <stdio.h>
int getData (char *which) {
int val;
printf ("Enter value for %s: ", which);
scanf("%d", &val);
return val;
}
void swapValues (int a, int b) {
printf("The swapped value of a is: %d\n", b);
printf("The swapped value of b is: %d\n", a);
}
int main (void) {
int a = getData ("a");
int b = getData ("b");
swapValues(a, b);
return 0;
}
You should also keep in mind that, if you actually want to swap the variables a and b and have that reflected back to main(rather than just print them as if they've been swapped), you'll need to pass pointers to them and manipulate them via the pointers.
C is a pass-by-value language meaning that changes to function parameters aren't normally reflected back to the caller. That would go something like this:
void swapValues (int *pa, int *pb) {
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
:
swapValues (&a, &b);
// a and b are now swapped.
You have unnecessarily complicated the whole thing.For one, something like return(a,b) is absurd in C.Further, if you intend to swap, why are you passing b as argument for the printf() meant to print 'a' and passing a to the printf() of 'b'?Anyways,here's a modified code that keeps it simple and gets the job done.
#include <stdio.h>
void swapValues()
{
int a, b,tem;
printf("Enter first number: ");
scanf("%d", &a);
printf("\nEnter second number: ");
scanf("%d", &b);
tem=a;
a=b;
b=tem;
printf("\nThe value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swapValues();
return(0);
}
First of all you can't return more than one value in C. The way around that is to return a struct or pass the values address.
void getData(int *a,int* b)
{
//int a, b;
printf("Enter first number: ");
scanf("%d", a); // look here you passed the address of a to scanf
// by doing that scanf can write to a
printf("Enter second number: ");
scanf("%d", b);
//return(a, b);
}
The old main:
int main()
{
int a, b = getData(); // b gets the return value from getData()
// but a is still uninitialized
//to call the new function you have to do the following
int a,b;
getData(&a,&b);
swapValues(a, b);
return(0);
}
You cannot return multiple values from a C function. I'm not even sure why the statement return(a, b) compiles.
If you want to return more than value from a function you should either put them into an array or a structure. I'm going to use a structure to demonstrate one way to do this correctly. There are many ways to do this, but this one modifies you code the least.
struct TwoNums{
int a;
int b;
};
TwoNums getData()
{
/* This creates a new struct of type struct TwoNums */
struct TwoNums nums;
printf("Enter first number: ");
scanf("%d", &(nums.a));
printf("Enter second number: ");
scanf("%d", &(nums.b));
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
/* Get the whole structure in one call */
struct TwoNums nums = getData();
/* Call the swap function using fields of the structure */
swapValues(nums.a, nums.b);
return 0;
}
The first:
getData() function is written incorrectly.
You can not return more than one parameter from the function in C. So you can to separate data reading, or use pointers as below:
void getData(int* a, int* b) {
printf("Enter first number: ");
scanf("%d", a);
printf("Enter second number: ");
scanf("%d", b);
}
In main()
int a, b;
getData(&a, &b);
The second:
swapValues(int a, int b) does not swap the data.
More correct:
void swapValues(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
without using temporary variable.
So try this code
#include <stdio.h>
int swape()
{
int a,b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
a=a+b;
b=a-b;
a=a-b;
printf("The value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swape();
return(0);
}

Resources