Pointer Exercise in C

Pointer Exercise in C

Question 1: Write a C program for the basic declaration of the pointer.

Solution:

#include <stdio.h>

int main()

{

    int i = 3;

    int *j = &i;

    printf("\n\nThe adress of the i is ---> %u\n", j);

    printf("\n\nThe value of the i is ---> %d\n", *j);

    

    return 0;

}

                You can check the code:- Check here


Question 2: Write the c program to show how the pointer handles the programe.

Solution:

#include <stdio.h>

int main()

{

   int* ab;

   int m;

   m=29;

    printf("\n\n Pointer : How to  handle the pointers in the program :\n"); 

    printf("------------------------------------------------------------\n");

    printf(" Here in the declaration ab = int pointer, int m= 29\n\n");

    

   printf(" Address of m : %p\n",&m);

   printf(" Value of m : %d\n\n",m);

   ab=&m;

   printf(" Now ab is assigned with the address of m.\n");

   printf(" Address of pointer ab : %p\n",ab);

   printf(" Content of pointer ab : %d\n\n",*ab);

   m=34;

   printf(" The value of m assigned to 34 now.\n");

   printf(" Address of pointer ab : %p\n",ab);

   printf(" Content of pointer ab : %d\n\n",*ab);

   *ab=7;

   printf(" The pointer variable ab is assigned the value 7 now.\n");

   printf(" Address of m : %p\n",&m);//as ab contain the address of m

                                     //so *ab changed the value of m and now m become 7

   printf(" Value of m : %d\n\n",m);

   return 0;

}

                    You can check the code:- Check here


Question 3: Write a program that finds sum and average using call by reference in C.

Solution: 

#include <stdio.h>

void sum_and_average(int *a, int *b, int *sum, float *avg)

{

    *sum= *a+*b;

    *avg= (float)(*sum)/2;

}

int main()

{

    int num1, num2, sum;

    float avg;

    printf("\n\nEnter two number--> ");

    scanf("%d%d", &num1, &num2);

    sum_and_average(&num1, &num2, &sum, &avg);

    printf("\n\n The sum is --> %d",sum);

    printf("\n\n The average is --> %0.2f",avg);

    return 0;

}

                You can check the code:-  Check here


Question 4: Write the program to find the max between two numbers entered by the user using pointer.

Solution:

#include<stdio.h>

void compare(int *p ,int *q){

    if (*p<*q)

    {

        printf("\n%d is the maximum number.\n",*q);

    }

    else if (*p>*q)

    {

        printf("\n%d is the maximum number.\n",*p);

    }

    else

    {

        printf("\nBoth are equal number.\n",*p);

    }

    

}

int main()

{

    int num1 , num2;

    printf("\n\tInput the first number : ");

    scanf("%d",&num1);

    printf("\n\tInput the second number : ");

    scanf("%d",&num2);

    printf("\n--------X--------------X---------------X------------\n");

    compare(&num1 , &num2);

    return 0;

}

                    You can check the code here.


Question 5: Write the program to enter N element in an array using the pointer and print as output 

Solution:

#include <stdio.h>

int main()

{

   int arr1[25], i,n;

   printf("\n\n Pointer : Store and retrieve elements from an array :\n"); 

   printf("------------------------------------------------------------\n");    

   printf(" Input the number of elements to store in the array :");

   scanf("%d",&n);

   

   printf(" Input %d number of elements in the array :\n",n);

   for(i=0;i<n;i++)

      {

  printf(" element - %d : ",i);

  scanf("%d",arr1+i);

  }

   printf(" The elements you entered are : \n");

   for(i=0;i<n;i++)

      {

  printf(" element - %d : %d \n",i,*(arr1+i));

  }

   return 0;

}

                        You can check the code:- Check here


Question 6: Write a program in C to print all permutations of a given string using pointers

Solution: 

#include <stdio.h>

#include <string.h>

  

//  Function to swap values at two pointers 

void swap(char* x, char* y)

{

    char temp;

    temp = *x;

    *x = *y;

    *y = temp;

}

  

void permute(char* a, int l, int r)

{

    int i;

    if (l == r)

        printf("%s\n", a);

    else {

        for (i = l; i <= r; i++) {

            swap((a + l), (a + i));

            permute(a, l + 1, r);

            swap((a + l), (a + i)); // backtrack

        }

    }

}


int main()

{

    char str[] = "ABCD";

    int n = strlen(str);

    permute(str, 0, n - 1);

    return 0;

}

                        You can check the code:- Check here

Question 7: Write the C program to find the largest element using Dynamic memory allocation.

Solution:

#include<stdio.h>

#include <stdlib.h>

int main(){

    int n;

    printf("Input total number of elements(1 to 100): ");

    scanf("%d",&n);

    float *ptr=(float*)calloc(n,sizeof(float));

    

    if(ptr==NULL)

    {

        printf(" No memory is allocated.");

        exit(0);

    }

    printf("\n");

    for(int i=0;i<n;++i)  

    {

       printf(" Number %d: ",i+1);

       scanf("%f",ptr+i);

    }

    for(int i=1;i<n;++i)  

    {

       if(*ptr<*(ptr+i)) 

           *ptr=*(ptr+i);

    }

    printf(" The Largest ptr is :  %.2f \n\n",*ptr);

    return 0;

}

        You can check the code:- Check here

Question 8: Write the C program to find the length of the string using a pointer.

Solution:

#include <stdio.h>

int main()

{

    char str[30];

    printf("\n--------------X------------X------------\n");

    printf("\nInput a string : ");

    gets(str);

    char *ptr = str;

    int l = 0 ;

    while (*ptr!='\0')

    {

        l++;

        ptr++;

    }

    

    printf("\nThe length of the given string %s is: %d",str,l);

    printf("\n--------------X------------X------------\n");


return 0;

}

                        You can check the code Check here

Question 9: Write the program to find reverse of a string using pointers.

Solution: 

#include <stdio.h>

#define MAX_SIZE 100 // Maximum string size


int main()

{

    char str[MAX_SIZE], reverse[MAX_SIZE];

    char *s = str;

    char *r = reverse;

    int len = 0;


    /* Input string from user */

    printf("Enter any string: ");

    gets(str);


    /* Find length of string */

    while(*(s++)) len++;


    /* 

     * Store each character from the end of the original string 

     * to reverse string

     */

    s--;

    while(len >= 0)

    {

        *(r++) = *(--s);

        len--;

    }

    *r = '\0';


    printf("\nOriginal string = %s\n", str);

    printf("Reverse string = %s", reverse);


    return 0;

}

                            You can check the code:- Check here


Question 10: Write program to access a two dimensional array using pointer.

Solution: 

#include <stdio.h>

#define ROWS 3

#define COLS 3

/* Function declaration to input and print two dimensional array */

void inputMatrix(int matrix[][COLS], int rows, int cols);

void printMatrix(int matrix[][COLS], int rows, int cols);

int main()

{

    int matrix[ROWS][COLS];

    int i, j;

    /* Input elements in matrix */

    printf("Enter elements in %dx%d matrix.\n", ROWS, COLS);

    inputMatrix(matrix, ROWS, COLS);

    /* Print elements in matrix */

    printf("Elements of %dx%d matrix.\n", ROWS, COLS);

    printMatrix(matrix, ROWS, COLS);

    return 0;

}

/**

 * Function to take input in two dimensional array (matrix) 

 * from user.

 *

 * @matrix  2D array to store input.

 * @rows    Total rows in 2D matrix.

 * @cols    Total columns in 2D matrix.

 */

void inputMatrix(int matrix[][COLS], int rows, int cols)

{

    int i, j;

    for(i = 0; i < rows; i++)

    {

        for(j = 0; j < cols; j++)

        {

            // (*(matrix + i) + j is equivalent to &matrix[i][j]

            scanf("%d", (*(matrix + i) + j));

        }

    }

}

/**

 * Function to display elements of the two-dimensional array (matrix)

 * on the console.

 *

 * @matrix  2D array to display as output.

 * @rows    Total rows in the 2D matrix.

 * @cols    Total columns in the 2D matrix.

 */

void printMatrix(int (*matrix)[COLS], int rows, int cols)

{

    int i, j;

    for (i = 0; i < rows; i++)

    {

        for (j = 0; j < cols; j++)

        {

            // *(*(matrix + i) + j) is equivalent to matrix[i][j]

            printf("%d ", *(*(matrix + i) + j));

        }


        printf("\n");

    }

}

                        You can check the code:- Check here


Question 11: Write program to swap two arrays using pointers.

Solution: 

#include <stdio.h>

#define MAX_SIZE 100    // Maximum array size

/* Function declarations */

void inputArray(int *arr, int size);

void printArray(int *arr, int size);

void swapArray(int *sourceArr, int *destArr, int size);

int main()

{

    int sourceArr[MAX_SIZE];

    int destArr[MAX_SIZE];

    int size;

    // Input array size

    printf("Enter size of array: ");

    scanf("%d", &size);

    // Input elements of destination array

    printf("Enter %d elements in source array: ", size);

    inputArray(sourceArr, size);

    // Input element of destination array

    printf("Enter %d elements in destination array: ", size);

    inputArray(destArr, size);

    /*

     * Print elements of both arrays before swapping

     */

    printf("\n\nSource array before swapping: ");

    printArray(sourceArr, size);

    printf("\nDestination array before swapping: ");

    printArray(destArr, size);

    /* Swap elements of both arrays. */

    swapArray(sourceArr, destArr, size);

    /*

     * Print elements of both arrays after swapping

     */

    printf("\n\nSource array after swapping: ");

    printArray(sourceArr, size);

    printf("\nDestination array after swapping: ");

    printArray(destArr, size);

    return 0;

}

/**

 * Function used to read input from user in an array.

 *

 * @arr     Pointer to array to store input

 * @size    Size of the array

 */

void inputArray(int *arr, int size)

{

    // Pointer to last element of array.

    int *arrEnd = (arr + (size - 1));

    // Input elements in array using pointer

    while(arr <= arrEnd)

        scanf("%d", arr++);

}

/**

 * Function used to print elements of array.

 * 

 * @arr     Pointer to array, which is to print.

 * @size    Size of the array

 */

void printArray(int *arr, int size)

{

    // Pointer to last element of array.

    int *arrEnd = (arr + (size - 1));

    // Print elements of array one by one

    while(arr <= arrEnd)

        printf("%d, ", *(arr++));

}

/**

 * Function to swap elements of two arrays.

 * @sourceArr       Pointer to source array to swap.

 * @destArr         Pointer to destination array to swap.

 * @size            Size of array.

 */

void swapArray(int * sourceArr, int * destArr, int size)

{

    // Pointer to last element of source array

    int * sourceArrEnd = (sourceArr + (size - 1));

    // Pointer to last element of destination array

    int * destArrEnd   = (destArr + (size - 1));

    /*

     * Swap individual element of both arrays

     */

    while(sourceArr <= sourceArrEnd && destArr <= destArrEnd)

    {

        *sourceArr ^= *destArr;

        *destArr   ^= *sourceArr;

        *sourceArr ^= *destArr;

        // Increment source array to point to next element

        sourceArr++;

        // Increment destination array to point to next element

        destArr++;

    }

}

                    You can check the code:- Check Here.


Question 12: Write program to sort an array using pointers.

Solution: 

#include <stdio.h>

#define MAX_SIZE 100

/* Function declaration */

void inputArray(int * arr, int size);

void printArray(int * arr, int size);

/* Sort function declaration */

int sortAscending(int * num1, int * num2);

int sortDescending(int * num1, int * num2);

void sort(int * arr, int size, int (* compare)(int *, int *));

int main()

{

    int arr[MAX_SIZE];

    int size;

    /*

     * Input array size and elements.

     */

    printf("Enter array size: ");

    scanf("%d", &size);

    printf("Enter elements in array: ");

    inputArray(arr, size);

    printf("\n\nElements before sorting: ");

    printArray(arr, size);

    // Sort and print sorted array in ascending order.

    printf("\n\nArray in ascending order: ");

    sort(arr, size, sortAscending);

    printArray(arr, size);

    // Sort and print sorted array in descending order.

    printf("\nArray in descending order: ");

    sort(arr, size, sortDescending);

    printArray(arr, size);

    return 0;

}

/**

 * Function to take input in array elements.

 * 

 * @arr     Array to store input.

 * @size    Size of the array.

 */

void inputArray(int * arr, int size)

{

    // Pointer to last element of array

    int * arrEnd = (arr + size - 1);

    // (arr++) Input in current array element and move to next element.

    // Till last array element (arr <= arrEnd)

    while(arr <= arrEnd)

        scanf("%d", arr++);

}

/**

 * Function to print all array elements.

 * 

 * @arr     Array to print.

 * @size    Size of the array.

 */

void printArray(int * arr, int size)

{

    // Pointer to last element of array

    int * arrEnd = (arr + size - 1);

    // *(arr++) Print current array element and move to next element.

    // Till last array element (arr <= arrEnd)

    while(arr <= arrEnd)

        printf("%d, ", *(arr++));

}

/**

 * Function to compare two successive elements.

 * The function returns the difference of the first and second integer.

 * 

 * @num1    First integer to compare.

 * @num2    Second integer to compare.

 *

 * @return  Difference of num1 and num2.

 */

int sortAscending(int * num1, int * num2)

{

    return (*num1) - (*num2);

}

/**

 * Function to compare two successive elements. 

 * The function returns the difference of the second and first parameters.

 *

 * @num1    First integer to compare.

 * @num2    Second integer to compare.

 *

 * @return  Difference of num2 and num1.  

 */

int sortDescending(int * num1, int * num2)

{

    return (*num2) - (*num1);

}

/**

 * Function to sort an array in ascending or descending order.

 * This function is used to sort array in both orders ascending or

 * descending.

 *

 * @arr     Array to sort.

 * @size    Size of the array.

 * @compare Function pointer returning an integer and takes two int * 

 *          parameter. The function is called to get the arrangement of

 *          two successive array elements.

 */

void sort(int * arr, int size, int (* compare)(int *, int *))

{

    // Pointer to last array element

    int * arrEnd  = (arr + size - 1);

    // Pointer to current array element

    int * curElem = arr;

    int * elemToSort;

    // Iterate over each array element

    while(curElem <= arrEnd)

    {

        elemToSort = curElem;

        // Compare each successive elements with current element

        // for proper order.

        while(elemToSort <= arrEnd)

        {

            /*

             * Compare if elements are arranged in order 

             * or not. If elements are not arranged in order

             * then swap them.

             */

            if(compare(curElem, elemToSort) > 0)

            {

                *curElem    ^= *elemToSort;

                *elemToSort ^= *curElem;

                *curElem    ^= *elemToSort;

            }

            elemToSort++;

        }

        // Move current element to next element in array.

        curElem++;

    }

}

                                You can check the code:- Check here.


Question 13: Write program to concatenate two strings using pointer.

Solution: 

#include <stdio.h>

#define MAX_SIZE 100 // Maximum string size

int main()

{

    char str1[MAX_SIZE], str2[MAX_SIZE];

    char * s1 = str1;

    char * s2 = str2;

    /* Input two strings from user */

    printf("Enter first string: ");

    gets(str1);

    printf("Enter second string: ");

    gets(str2);

    /* Move till the end of str1 */

    while(*(++s1));

    /* Copy str2 to str1 */

    while(*(s1++) = *(s2++));

    printf("Concatenated string = %s", str1);

    return 0;

}

                                    You can check the code:- Check here.


Post a Comment

0 Comments