Write a program that contains both a main function and a fun

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 will 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 (*). This exercise is similar to the exercise for which you have filled in a memory template. Try to re-write this program without looking at the solution. You need to learn how to deal with pointers as a simulation of call by reference in C. Don\'t look at the solution, be honest with yourself!

Solution

The program is as follows:

#include <stdio.h>
//swap function declaration
void swap(int *a, int *b);
//main function declaration
int main()
{
int num1, num2;
   printf(\"Enter the value of num1 and num2 to be swapped\ \");
   scanf(\"%d%d\",&num1,&num2);
printf(\"before swap\ \");
printf(\"Number1 = %d\ \", num1);
printf(\"Number2 = %d\ \", num2);
// address of num1 and num2 is passed to the swap function defined in the program
swap( &num1, &num2);
   printf(\"After swap\ \");
printf(\"Number1 = %d\ \", num1);
printf(\"Number2 = %d\ \", num2);
return 0;
}
//calling swap function
void swap(int * a, int * b)
{
// pointer n1 and n2 points to the address of num1 and num2 respectively
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}

 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 c

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site