Call by Value and Call by Reference

Algorithm

Step 1: Start

Step 2: Declare variable a = 5 and choice

Step 3: Display menu to choose between call by value or call by reference

Step 4: Read user input into choice

Step 5: Display initial value of a

Step 6: Use switch case to check choice

Step 7: If choice is 1, call modifyValue1(a)

Step 8: If choice is 2, call modifyValue2(&a)

Step 9: Print value of a after function call

Step 10: End

Flowchart

graph TD; A([Start]) --> B["Declare a = 5, choice"]; B --> C[/Display menu/]; C --> D[/Read choice/]; D --> E[/Display initial a/]; E --> F{"Choice == 1 or 2"}; F -->|1| G["Call modifyValue1(a)\nto change value"]; F -->|2| H["Call modifyValue2(&a)\nto change value by address"]; G --> I[/Print a/]; H --> I; I --> J([End]); classDef start fill:#00cc44,stroke:#006622,stroke-width:2px,color:#ffffff; classDef stop fill:#ff4444,stroke:#cc0000,stroke-width:2px,color:#ffffff; classDef io fill:#ffdd44,stroke:#cc9900,stroke-width:2px,color:#000000; classDef process fill:#4488ff,stroke:#0044cc,stroke-width:2px,color:#ffffff; classDef decision fill:#ff8844,stroke:#cc4400,stroke-width:2px,color:#ffffff; class A start; class J stop; class C,D,E,I io; class B,G,H process; class F decision;

Program

/* Call by value and Call by Reference */
#include <stdio.h>

void modifyValue1(int x) 
{
    x = 10; // Won't affect original
} 

void modifyValue2(int *x)
{
    *x = 10; // Affects original
}

int main()
{
    int a = 5, choice;
    printf("Enter your option:\n 1.Call by value\n 2.Call by reference\n Type Number (1 or 2): ");
    scanf("%d", &choice);

    printf("Initial value of a = %d", a);

    switch (choice)
    {
        case 1:
            modifyValue1(a);
            printf("\nAfter calling modifyValue1: a = %d", a);
            break;
        case 2:
            modifyValue2(&a);
            printf("\nAfter calling modifyValue2: a = %d", a);
            break;
        default:
            printf("Wrong option, Type 1 or 2 only.");
    }

    return 0;
}
                

Test Case Output
Enter your option:
 1.Call by value
 2.Call by reference
 Type Number (1 or 2): 1
Initial value of a = 5
After calling modifyValue1: a = 5

-------------------------------

Enter your option:
 1.Call by value
 2.Call by reference
 Type Number (1 or 2): 2
Initial value of a = 5
After calling modifyValue2: a = 10