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);
}
Related
I want to Prompt the user to enter 3 numbers. Then, swap the first number with the second one, the second number with the third and the third with the first by calling a function called "swap".
Functions in C cannot return more than one value so I decided to create a structure with pointers that I will later use in my function. Then, I created three-pointers that will store the address of each one of the numbers so I can dereference to these numbers in my function (as shown below)
Number.pa = *ppb;
Number.pb = *ppc;
Number.pc = *ppa;
Here's my code:
#include <stdio.h>
void swap(); // a = b, b = c, c = a
struct Numbers {
int *pa, *pb, *pc;
} ;
int main(void) {
struct Numbers Number; // Structure to hold the values of the three variables.
int a, b, c;
int *ppa, *ppb, *ppc;
printf("\n Please enter three integer numbers: ");
scanf("%d%d%d", &a, &b, &c);
ppa = &a; ppb = &b; ppc = &c;
swap(a, b, c, Number, *ppa, *ppb, *ppc);
printf("\n %d \t %d \t %d \n", Number.pa, Number.pb, Number.pc);
}
void swap(int a, int b, int c, struct Numbers Number, int *ppa, int *ppb, int *ppc) {
Number.pa = *ppb;
Number.pb = *ppc;
Number.pc = *ppa;
} ;
Most of the arguments to your swap function are either pointless or the work of sheer guessing (or both). The assignment effectively wants you to "rotate" values from a through c. So do that, and only that.
#include <stdio.h>
void swap(int *pa, int *pb, int *pc);
int main()
{
int a, b, c;
printf("\n Please enter three integer numbers: ");
if (scanf("%d %d %d", &a, &b, &c) == 3)
{
swap(&a, &b, &c);
printf("%d %d %d \n", a, b, c);
}
return 0;
}
void swap(int *pa, int *pb, int *pc)
{
int tmp = *pa;
*pa = *pb;
*pb = *pc;
*pc = tmp;
}
Stop reading more into an assignment than is there. If it sounds simple, it probably is. The warning was due to passing the value of dereferenced pointers to int (so int values) to a function expecting int pointers; not int values. As you can see, you don't need to do any of that (and didn't in the first place).
Hello there I am learning pointers so I created a calculator.
I managed to return the value and the pointers from a function but by declaring them globally. How can I declare them locally?
#include <stdio.h>
#include <stdlib.h>
Declaration of all functions
int Addition();
int Subtraction();
int Devision();
int Multiplication();
Declaration of Global Variables, which I would like to declare them locally
int p;
int n;
int *r=&n;
int *b=&p;
Start of main Function
int main()
{
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
The user chooses an Arithmetic operation (function) by inputting one number(1,2,3,4 or 0 for Exit)
if (g==1)
{
s=Addition(r,b);
printf("The addition result is %d+%d=%d",*r, *b, s);
}
else if (g==2)
{
s=Subtraction(r,b);
printf("The Subtraction result is %d-%d=%d",*r, *b, s);
}
else if (g==3)
{
s=Devision(r,b);
printf("The Devision result is %d/%d=%d",*r, *b, s);
}
else if (g==4)
{
Multiplication(r,b);
printf("The Multiplication result is %d/%d=%d",*r, *b, s);
}
else
{
break;
}
return 0;
}
}
End of main function.
Below are all the other functions
Addition()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n+p;
return x;
}
Subtraction()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n-p;
return x;
}
Devision()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n / p;
return x;
}
Multiplication()
{
int x;
printf("Ennter first nr: ");
scanf("%d",&n);
printf("Ennter second nr: ");
scanf("%d",&p);
x=n * p;
return x;
}
1) Refresh the knowledge about pointers and pass parameters via pointers if you want to.
The indirection or dereference operator * gives the contents of an object pointed to by a pointer.
The unary or monadic operator & gives the address of a variable.
2) Avoid global variables declare them locally after main.
3) Use switch instead of if-else chains
#include <stdio.h>
#include <stdlib.h>
int Addition(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x = *n + *p;
return x;
}
int Subtraction(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x = *n - *p;
return x;
}
int main(void)
{
int n1 = 0;
int n2 = 0;
int *r = &n1;
int *b = &n2;
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
switch(g)
{
case 0:
printf("END\n");
return 0;
break;
case 1:
s = Addition(r, b);
printf("The addition result is: %d+%d=%d\n\n",n1, n2, s);
break;
case 2:
s = Subtraction(r ,b);
printf("The Subtraction result is: %d-%d=%d\n\n",*r, *b, s);
break;
}
}
return 0;
}
Test:
Please choose the Arithmetic operation:
Addition-> 1
Subtraction-> 2
Devision-> 3
Multiplication-> 4
Exit-> 0
2
Ennter first nr: 5
Ennter second nr: 3
The Subtraction result is: 5-3=2
Please choose the Arithmetic operation:
Addition-> 1
Subtraction-> 2
Devision-> 3
Multiplication-> 4
Exit-> 0
0
END
I used them Globally because it was easier for me to call and read them. That is why I want to learn how can I declare them locally.
Very simply, just declare them locally, as shown: (without your user input code to focus on your primary question)
int main(void)
{ // locally declared
double a = 4.5;
double b = 10.8;
double result_1, result_2, result_3, result_4;
result_1 = add(a, b);
result_2 = sub(a, b);
result_3 = mul(a, b);
result_4 = div(a, b);
return 0;
}
// example function (the others will be of similar form,
// a single return line with the appropriate math operator.
double add(double a, double b)//no pointers necessary
{
return a + b;
}
If you really want to use a pointer, then you can implement the function to return the result via an argument:
void add(double a, double b, double *result)
{
*result = a + b;
}
Usage: (call from main for example)
add(a, b, &result_1);// passing the address of result_1
// to allow the value at that address
// to be modified.
Well, not sure if this is what you are asking for, but let me suggest you this code:
#include <stdio.h>
#include <stdlib.h>
int Addition(int* n, int* p)
{
int x;
printf("Ennter first nr: ");
scanf("%d",n);
printf("Ennter second nr: ");
scanf("%d",p);
x=*n+*p;
return x;
}
int main()
{
int n1=0;
int n2=0;
int *r=&n1;
int *b=&n2;
int g,s;
while (1)
{
printf("Please choose the Arithmetic operation: \n");
printf("Addition-> 1 \nSubtraction-> 2 \nDevision-> 3 \nMultiplication-> 4 \nExit-> 0\n ");
scanf("%d",&g);
if (g==1)
{
s=Addition(r,b);
printf("The addition result is %d+%d=%d",*r, *b, s);
}
return 0;
}
}
As you can see, we are using pointers to store the value of the number written by the user, so you can keep them after calling the function.
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.
So, I've been trying to get two integers from the user and the program should return the value of the larger one. Here is my sample program:
#include<stdio.h>
int larger(int a, int b);
int main()
{
int num1, num2;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("\n%d is larger than the other", larger(num1, num2) );
}
int larger(int a, int b)
{
if (a>b)
{
printf("%d", a);
}
else if(b>a){
printf("%d", b);
}
}
But the problem here is that whenever I compile then run the program an integer value of 1 is placed beside the sentence "is larger than the other" ,while the largest integer (the integer that should be beside the 'is larger than the other') is placed above the integer 1.
SAMPLE OUTPUT:
Enter first number: 5
Enter second number: 3
5
1 is larger than the other
What should I do to place the larger value placed where it should be?
int larger(int a, int b)
Your function doesn't have a return statement . If you want largest value between two you need to return it from function . Like this -
int larger(int a, int b)
{
if (a>b)
{
//printf("%d", a); unnecessary as you print value in main
return a;
}
else if(b>a){
//printf("%d", b);
return b;
}
else
return a; //in this case take care of output message as both variables will be equal
}
larger needs to actually return the larger value: write return a;, and return b; in the appropriate places. And the output will look odd if you retain the printf calls in that function.
Currently your program behaviour is undefined as the return value is missing: the output is currently arbitrary.
You're also not dealing with all possibilities. What should happen if a and b are equal? You must return something on all control paths.
Your function isn't returning anything, you need to enable compiler warnings or alternatively, get a new compiler.
That being said, in case you aren't afraid of boolean logic, the function can simply be written as
static inline bool larger (int a, int b)
{
return a > b;
}
Naturally, you'll have to rewrite main() to check the result:
if(larger (x, y))
{
printf("x larger than y");
}
In int function larger(int a, int b) you should just compare and return the value rather than printing it.
#include<stdio.h>
int larger(int a, int b);
int main()
{
int num1, num2, largeOftheTwo= 0;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
if(num1 != num2)
printf("\n%d is larger than the other", larger(num1, num2));
else
printf("\n%d is equal to %d", num1, num2);
return 0;
}
int larger(int a, int b)
{
if (a>b)
return a;
else
return b;
}
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