Design an algorithm, draw a corresponding flow chart and write a program in C, to swap the values using pass by value and pass by reference methods. 10m Jun2007

By | July 11, 2014

Design an algorithm, draw a corresponding flow chart and write a program in C, to swap the values using pass by value and pass by reference methods. 10m Jun2007

 FlowChart:

FlowChart_Swap_Reference

Program to swap two values (Pass By Value):-

#include <stdio.h>
main ( )
{
int x = 2, y = 3;
clrscr();
void swap(int, int);
printf (“\n Values before swapping are %d %d”, x, y);
swap (x, y);
printf (“\n Values after swapping are %d %d”, x, y);
getch();
}
void swap( int a, int b )
{
int t;
t = a;
a = b;
b = t;
}

#include <stdio.h>
main ( )
{
int x = 2, y = 3;
clrscr();
void swap(int, int);
printf (“\n Values before swapping are %d %d”, x, y);
swap (x, y);
printf (“\n Values after swapping are %d %d”, x, y);
getch();
}
void swap( int a, int b )
{
int t;
t = a;
a = b;
b = t;
}

OUTPUT

Values before swap are 2 3

Values after swap are 2 3

But the output should have been 3 2. So what happened?

The value can only be changed by pass by Reference method as the change is limited to Function Only by pass by Value.

Program to swap two values (Pass By Reference):-

# include <stdio.h>

void main()
{
int M,N;
void swapRef ( int *, int * );
clrscr();
printf(“ENTER M : “);
scanf(“%d”,&M);
printf(“ENTER N : “);
scanf(“%d”,&N);
printf (“\nBefore calling function swapRef M=%d N=%d”,M,N);
swapRef (&M,&N); /*address of arguments are passed */
printf(“\nAfter calling function swapRef M=%d N=%d”,M,N);
getch();
}
void swapRef (int *pm, int *pn)
{
int temp;
temp = *pm;
*pm = *pn;
*pn = temp;
printf (“\nWithin function swapRef *pm=%d *pn=%d”,*pm,*pn);
return;
}

# include <stdio.h>
void main()
{
int M,N;
void swapRef ( int *, int * );
clrscr();
printf("ENTER M : ");
scanf("%d",&M);
printf("ENTER N : ");
scanf("%d",&N);
printf ("\nBefore calling function swapRef M=%d N=%d",M,N);
swapRef (&M,&N); /*address of arguments are passed */
printf("\nAfter calling function swapRef M=%d N=%d",M,N);
getch();
}
void swapRef (int *pm, int *pn)
{
int temp;
temp = *pm;
*pm = *pn;
*pn = temp;
printf ("\nWithin function swapRef *pm=%d *pn=%d",*pm,*pn);
return;
}

 

Screen Shots:

SWAP

 

SWAP_Output

 

 

Write an algorithrn and program in C to print fibonacci series 10m Jun2007

Solved program can be found on this link http://cssimplified.com/c-programming/design-an-algorithm-draw-a-corresponding-flow-chart-and-write-a-program-in-c-to-print-the-fibonacci-series-10m-jun2006

Leave a Reply