Programs on Pointers

 

1.Write a program to read two integers using pointers and perform all arithmetic operations on them.

#include<stdio.h>

int main()

{

          int no1,no2;

          int *ptr1,*ptr2;   

        int sum,sub,mult;

        float div;   

    printf("Enter number1:\n");

    scanf("%d",&no1);

    printf("Enter number2:\n");

    scanf("%d",&no2);

    

    ptr1=&no1;//ptr1 stores address of no1

    ptr2=&no2;//ptr2 stores address of no2

    

    sum=(*ptr1) + (*ptr2);

    sub=(*ptr1) - (*ptr2);

    mult=(*ptr1) * (*ptr2);

    div=(*ptr1) / (*ptr2);

    

    printf("sum= %d\n",sum);

    printf("subtraction= %d\n",sub);

    printf("Multiplication= %d\n",mult);

    printf("Division= %f\n",div);

 

    return 0;

}

Output-

 

Q.2 Write a program to accept an integer using pointer and check whether it is even or odd.

#include<stdio.h>

int main()

{

  int num;

  int *pnum;

  printf("Enter number: ");

  scanf("%d",&num);

  pnum= &num;

  if(*pnum % 2==0)

    printf("%d is even.\n", *pnum);

  else

    printf("%d is odd.\n", *pnum);

  return 0;

}

 

Q.3 Program to Find Maximum Between Two Numbers Using Pointers:

 

#include<stdio.h>

int main()

{

          int no1,no2;

          int *ptr1,*ptr2;

         

          printf("Enter first number:\n");

          scanf("%d",&no1);

          printf("Enter second number:\n");

          scanf("%d",&no2);

          ptr1=&no1;/*ptr1 stores address of no1*/

          ptr2=&no2;/*ptr2 stores address of no2*/

          if(*ptr1>*ptr2)

          {

          printf("Maximum number is %d",*ptr1);

          }

          else

          {

          printf("Maximum number is %d",*ptr2);

          }

        return 0;

}

 

Q.4 Write a program to interchange two numbers using pointers.

 

#include <stdio.h>

int main() {

    int a, b, temp;

    int *ptr1, *ptr2;

    printf("Enter the value of a and b: ");

    scanf("%d %d", &a, &b);

    printf("\nBefore swapping a = %d and b = %d", a, b);

    // Assign the memory address of a and b to *ptr1 and *ptr2

    ptr1 = &a;

    ptr2 = &b;

    // Swap the values a and b

    temp = *ptr1;

    *ptr1 = *ptr2;

    *ptr2 = temp;

    printf("\nAfter swapping a = %d and b = %d", a, b);

    return 0;

}

 

 

 

Comments

Popular posts from this blog

Slip 11: Write node js application that transfer a file as an attachment on web and enables browser to prompt the user to download file using express js.

Slip 7 Create a node js file named main.js for event-driven application. There should be a main loop that listens for events, and then triggers a callback function when one of those events is detected.

Slip 1(a) Write an Angular 13 application addition of two numbers using ng-init, ng-model & ng-bind. And also demonstrate ng-show, ng-disabled, ng-click directives on button component.