Get all semester notes for Computer Engineering here.

Write a C Program to swap numbers using third variable

Write a C program to swap values of two variable using third variable with algorithm and flowchart

Alogrithm:

    
        1. Start
        2. Define a=20,b=30,temp
        3. Display a,b before swap
        4. temp = b
        5. b = a
        6. a = temp
        7. Display a,b after swap
        8. Stop

Flowchart:

The a = b in the rectangle is actually a = temp{alertInfo}


Code:

        
        #include<stdio.h>
        int main(){
                int a=20,b=30,temp;
                printf(“a=%d and b= %d before swapping.”, a,b);
                temp = b;
                b = a;
                a = temp;
                printf(“a= %d and b=%d after swapping.”, a,b);
            }{codeBox}

Explanation:

        The value of a is 20 and b is 30 at first. A temporary variable temp is assigned. The value of temp is passed to temp and a is passed to b and again the value of temp is passed to a. In this way, the values get swapped.

Before:
a = 20;
b = 30;

temp = b;  //temp becomes 30
b = a; //b becomes 20
a = temp; //a becomes 30

After:
a = 30;
b = 20;


I am into computer science.

Post a Comment

Feel free to comment.