ANSWER REQUIRED IN C. Write a program that contains both a main function and a f
ID: 3807564 • Letter: A
Question
ANSWER REQUIRED IN C.
Write a program that contains both a main function and a function called swap. Your main program should read in two integer values from the keyboard and then call the function swap. The swap function will swap the original values and then return back to main. The function main wall then output the values contained in the original variables. The original values should be swapped. No global variables are to be used. You must simulate call by reference by passing the address of the variables to the function swap. You must be able to do this. Do not use an array. I want you to practice using the address operator (&) and the dereference operator (*). You need to learn how to deal with pointers as a simulation of call by reference in C.Explanation / Answer
#include <stdio.h>
int swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a,b;
printf("Enter the first integer: ");
scanf("%d", &a);
printf("Enter the second integer: ");
scanf("%d", &b);
printf("Values before swapping A = %d and B = %d ", a, b);
swap(&a, &b);
printf("Values after swapping A = %d and B = %d ", a, b);
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Enter the first integer: 5
Enter the second integer: 4
Values before swapping A = 5 and B = 4
Values after swapping A = 4 and B = 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.