Define a function named SwapValues that takes four integers as parameters and swaps the first with the second, and the third with the fourth values.

Define a function named SwapValues that takes four integers as parameters and swaps the first with the second, and the third with the fourth values. Then write a main program that reads four integers from input, calls function SwapValues() to swap the values, and prints the swapped values on a single line separated with spaces. programming c please

The Correct Answer and Explanation is:1

Here is the correct C program that defines a function SwapValues to swap values as described, along with an explanation:

C Program

#include <stdio.h>

// Function to swap two values using pointers
void SwapValues(int *a, int *b, int *c, int *d) {
    int temp;

    // Swap first and second
    temp = *a;
    *a = *b;
    *b = temp;

    // Swap third and fourth
    temp = *c;
    *c = *d;
    *d = temp;
}

int main() {
    int num1, num2, num3, num4;

    // Read four integers
    scanf("%d %d %d %d", &num1, &num2, &num3, &num4);

    // Call function to swap values
    SwapValues(&num1, &num2, &num3, &num4);

    // Print swapped values
    printf("%d %d %d %d\n", num1, num2, num3, num4);

    return 0;
}

This C program demonstrates how to swap pairs of integers using a function and pointers.

The function SwapValues is designed to take four integer pointers as its parameters. These pointers allow the function to directly access and modify the original variables passed from main. Inside the function, a temporary variable temp is used to perform the swapping:

  1. First, it swaps the values pointed to by a and b, which correspond to the first and second integers.
  2. Next, it swaps the values pointed to by c and d, which are the third and fourth integers.

The main function starts by declaring four integers (num1, num2, num3, num4). It reads their values using scanf, which takes input from the user.

The SwapValues function is then called with the addresses of these four integers using the address-of operator (&). This allows the function to modify the actual values in memory rather than working on local copies.

Finally, after the swapping, the new values are printed out in a single line using printf.

This approach uses pointers to enable pass-by-reference in C, allowing changes made in the function to reflect in the calling environment. It’s a fundamental concept in C programming, often used for manipulating values in memory, modifying arrays, or managing dynamic data structures.

This program is efficient and demonstrates core C concepts like functions, pointers, and standard input/output.

Scroll to Top