In this program, we are going to show you how to write a C Program to Swap Two Numbers Using Functions. So first we have to know about the functions. There are two types of Functions that are pre-defined functions.
These pre-defined functions are also known as library functions which are declared in the header files of C Programming such as gets(), print(), and scanf(). And another type of function is called user-defined functions.
User-defined functions are those functions that are created by users and use that function many times in their programs. These functions are further divided into 4 types but we are not discussing the introduction of C functions. We are here to write and understand the program of function by the simplest type of function.
C Program to Swap Two Numbers Using Functions:
In this program, we are using the simplest type of C functions without return type and without passing arguments. The syntax of this type of function is void function_name(void_arguments).
First, we have to declare the function and then the logic of the function will be written inside the definition of the function. In the function definition, we declare the variable a b, and k.
We will take the value of a and b from the user and k will be initialized to 0. We give the value of a to k, then a is equal to b means that the value of b will be assigned to the variable a, and then assign the value of k to b. So, this is the simplest logic of the swapping program or a function.
In this type of function the print and scanf(), statements will be inside the body of the function definition and the function call will be in the main function.
Program to Swap Two Numbers Using Functions:
#include<stdio.h> void swap(void); void swap(){ int a,b,k=0; printf("Enter the Value of a and b :\n"); scanf("%d %d",&a,&b); printf("Before Swapping\n"); printf("a=%d\nb=%d\n",a,b); k=a; a=b; b=k; printf("After Swapping\n"); printf("a=%d\nb=%d\n",a,b); } int main(){ swap(); return 0; }
Output:
Conclusion:
From the above program, we concluded how to write a C Program to Swap Two Numbers Using Functions and the above image show the output of the program. Suppose you are searching for a program to find the cube of a number using the function. Then click on the link Cube of a number using functions.