learn-c-programming

Pointer Questions

ComputeNepal - learn-c-programming stars - learn-c-programming forks - learn-c-programming

License issues - learn-c-programming

contributions - welcome

Learn C Programming

1. WAP to check even or odd numbers using pointer.

Program

//WAP to check even or odd numbers using pointer.

#include <stdio.h>
int check(int*);
int main(){
    int a;
    int *pt = &a;
    printf("Enter a number: ");
    scanf("%d", &a);
    check(pt);
    return 0;
}
int check(int *pt){
    if(*pt % 2 == 0){
        printf("Even\n");
    }
    else{
        printf("Odd\n");
    }
    return 0;
}

This is a C program that checks if a given number is even or odd using pointers. Here’s how it works:

So essentially, the program is using a pointer to pass the address of the integer variable to the check() function, so that it can access and manipulate the value of the variable directly. This allows the function to check whether the number is even or odd without needing to return a value.

2. WAP to swap two numbers using pointer.

Program

//WAP to swap two numbers using pointer.

#include <stdio.h>
int swap(int *, int *);
int main(){
    int a, b;
    int *ptr1 = &a, *ptr2 = &b;
    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);
    printf("Before Swap:\na = %d\tb = %d\n", a, b);
    swap(ptr1, ptr2);
    printf("After Swap:\na = %d\tb = %d\n", a, b);
    return 0;
}
int swap(int *ptr1, int *ptr2){
    int temp;
    temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;
    return 0;
}

This program swaps the values of two numbers entered by the user using pointers.

Here’s how it works:

The swap function works by using pointer arithmetic to access the values of the integers pointed to by ptr1 and ptr2. The values are swapped using a temporary variable to avoid losing any data during the swap. The original variables a and b are modified indirectly by the function through their pointers.

License

Released under MIT by @ComputeNepal.

Website - Visit ComputeNepal