PRACTICAL PROGRAMS:
Program 1: Write a C program to swap the two values using pointers.
#include <stdio.h>
void swap(int* a, int* b);
int main( )
{
int x = 10, y = 5;
printf("before function call value of x & y:");
printf("\nx = %d", x);
printf("\ny = %d", y);
swap(&x, &y);
printf("\nafter function call value of x & y:");
printf("\nx = %d", x);
printf("\ny = %d", y);
return 0;
}
void swap(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
before function call value of x & y:
x = 10
y = 5
after function call value of x & y:
x = 5
y = 10
Program 2: Write a program to access array elements using pointer.
#include <stdio.h>
void main( )
{
int *p, sum = 0, i = 0;
int x[5] = {5,9,6,3,7};
p=x; //store array address in p
printf("Element value Address\n");
while(i<5)
{
printf("x[%d] %d %u\n", i, *p, p);
sum = sum + *p;
i++;
p++;
}
printf("Sum = %d\n", sum);
printf("&x[0] = %u\n", &x[0]);
printf("p = %u\n", p);
}
Output:
Element value Address
x[0] 5 65514
x[1] 9 65516
x[2] 6 65518
x[3] 3 65520
x[4] 7 65522
Sum = 30
&x[0] = 65514
p = 65524
Program 3: Write a program for sorting using pointer.
#include <stdio.h>
void main( )
{
int a[5] = {2, 10, 6, 7, 8};
int *p, i = 0, j = 0;
p = &a[0];
for( i = 0 ; i < 9 ; i++)
{
for( j = i+1; j < 9 ; j++)
{
if( *( p + i ) > *( p + j ) )
{
*(p+i) = *(p+i) + *(p+j);
*(p+j) = *(p+i) - *(p+j);
*(p+i) = *(p+i) - *(p+j);
}
}
}
printf("Sorted Values : ");
for( i = 0 ; i < 10 ; i++)
{
printf("%d \t",*(p+i));
}
}
Output:
Sorted Values : 2 6 7 8 10
PRACTICE PROGRAMS:
Practice Program 1: Write a C program to print the address of character and the character of string using pointer.
#include<stdio.h>
int main()
{
char str[50];
char *ch;
int i = 0;
printf("Enter String : ");
gets(str);
ch = str;
while( *ch != '\0' )
{
printf("\n Position : %u Character : %c", ch, *ch);
ch++;
}
return 0;
}
Output:
Enter String : hello
Position : 6421984 Character : h
Position : 6421985 Character : e
Position : 6421986 Character : l
Position : 6421987 Character : l
Position : 6421988 Character : o