Write a C program that swaps two float numbers using functions

Swap Two Float Numbers Using Functions in C

In this tutorial, we will write a C program to swap two floating-point numbers using a function.

Problem Statement

Write a C program that swaps two float numbers using a user-defined function.

Understanding the Concept

To swap two numbers using a function, we use call by reference (using pointers). This allows the function to modify the original variables.

C Program


#include <stdio.h>

// Function to swap two float numbers
void swap(float *x, float *y) {
    float temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

int main() {
    float a, b;

    printf("Enter two float numbers: ");
    scanf("%f %f", &a, &b);

    printf("Before swapping:\n");
    printf("a = %.2f, b = %.2f\n", a, b);

    // Function call
    swap(&a, &b);

    printf("After swapping:\n");
    printf("a = %.2f, b = %.2f\n", a, b);

    return 0;
}

Explanation

1. Function Declaration

The function swap(float *x, float *y) takes two pointer arguments.

2. Swapping Logic

  • Store value of *x in a temporary variable.
  • Assign *y to *x.
  • Assign temporary value to *y.

3. Function Call

We pass the addresses of a and b using:


swap(&a, &b);

This allows the function to change the original values.

Sample Input

Enter two float numbers: 5.5 9.8

Output

Before swapping:
a = 5.50, b = 9.80
After swapping:
a = 9.80, b = 5.50

Time Complexity

The program performs a constant number of operations. So, the time complexity is O(1).

C program to swap two float numbers, swapping using function in C, call by reference in C language, pointer example in C, C programming function problems with solution

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন