Problem-01

author
By Supreme2023-09-24
Problem Statement :
Introduction to pointers. Call by Value and Call by reference.
Code:

#include <stdio.h>

void cvinterchange(int a, int b);
void crinterchange(int *a, int *b);

int main(){
int a,b;

printf("Enter The Value Of A : ");
scanf("%d",&a);

printf("\nEnter The Value Of B : ");
scanf("%d",&b);

cvinterchange(a,b);
printf("\n\n");
crinterchange(&a,&b);

return 0;
}

void cvinterchange(int a, int b){
printf("\n<---------Call By Value--------->");
printf("\nBefore Interchange A = %d B = %d",a ,b);
int c = a;
a = b;
b = c;
printf("\nAfter Interchange A = %d B = %d",a ,b);
}

void crinterchange(int *a, int *b){
printf("\n<-------Call By Reference------->");
printf("\nBefore Interchange A = %d B = %d",*a ,*b);
int c = *a;
*a = *b;
*b = c;
printf("\nAfter Interchange A = %d B = %d",*a ,*b);
}

Description :

Main Function:

  • Declares two integer variables, a and b.
  • Asks the user to input values for a and b.
  • Calls the cvinterchange function with a and b for Call By Value interchange.
  • Prints a newline for separation.
  • Calls the crinterchange function with the addresses of a and b for Call By Reference interchange.

cvinterchange Function (Call By Value):

  • Displays a message indicating it's using Call By Value.
  • Prints the values of a and b before the interchange.
  • Swaps the values of a and b using a temporary variable c.
  • Prints the values of a and b after the interchange.

crinterchange Function (Call By Reference):

  • Displays a message indicating it's using Call By Reference.
  • Prints the values pointed to by a and b before the interchange.
  • Swaps the values pointed to by a and b using a temporary variable c.
  • Prints the values pointed to by a and b after the interchange.

In this code, the main function is the entry point, and it calls two separate functions, cvinterchange and crinterchange, to demonstrate the difference between Call By Value and Call By Reference. The values of a and b are interchanged within these functions using different methods, and the results are printed to the console to illustrate the differences in how the two methods handle variable values.

Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.