LearnFrenzy
Sign in Take a free test

Pointers · Pointer Programs · Question 1

C program to swap two numbers using pointers Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a function swap() that swaps two integers using pointers, and call it from main().

Solution
main.c
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int a = 10, b = 20;
    printf("Before: a = %d, b = %d\n", a, b);
    swap(&a, &b);
    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}

Output Verified by compiling and running

Before: a = 10, b = 20
After:  a = 20, b = 10

The function receives the addresses of a and b, so writing through *a and *b changes the caller's variables. A swap that takes plain ints would only swap its own copies.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links