Write a program with two functions: main and swap. The main function will read t
ID: 3641808 • Letter: W
Question
Write a program with two functions: main and swap. The main function will read two integer numbers (the first read into a variable called x while the second read into a variable called y) and then calls the function swap that accepts two values and store them into the variables x and y respectively. The swap function should swap the value of the two variables. The main function should then print the values of the variables x and y.1. Write the program using variables x and y as local variables in both main and swap functions. Will the values of x and y in the main function be swapped?
In this case, the values of x and y in the main function will not be swapped since you are only passing values (not the memory location) to the swap function. In addition, swapping is only done on the local variables of the swap function and not on the variables of main.
2. One way to solve this problem (which is usually not a good programming practice but just for this lab we are going to use this technique to learn about global variables) is to use global variables instead of local variables. Rather than having variables x and y defined locally in both functions, define them once as global variables. Run your program and then make sure that the swapping of the two values now works properly.
Sample Run:
Enter the first number
80
Enter the second number
70
The value for x is: 80.
The value for y is: 70.
After swapping:
The value for x is: 70.
The value for y is: 80.
Explanation / Answer
#include #include void swap(); int x,y; void main() { clrscr(); printf("Enter first number : "); scanf("%d",&x); printf("Enter second number : "); scanf("%d",&y); printf("The value for x is : %d The value for y is : %d ",x,y); printf("After swapping "); swap(x,y); printf("The value for x is : %d The value for y is : %d ",x,y); getch(); } void swap(int a,int b) { int c; c=a; a=b; b=c; x=a; y=b; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.