[go: up one dir, main page]

0% found this document useful (0 votes)
6 views3 pages

Pointer Lab Exercises

Uploaded by

sarangceb91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Pointer Lab Exercises

Uploaded by

sarangceb91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Pointer Lab Exercises in C

1. Swap the values of two variables using pointers


#include <stdio.h>

int main() {
int a, b, temp;
int *p1, *p2;

printf("Enter two integers: ");


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

p1 = &a;
p2 = &b;

temp = *p1;
*p1 = *p2;
*p2 = temp;

printf("After swapping: a = %d, b = %d\n", a, b);


return 0;
}

2. find the maximum and minimum elements in a 1D array using pointers.

#include <stdio.h>

int main() {
int arr[100], n, i;
int *p;
int max, min;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
p = arr; // pointer points to the first element
max = min = *p;
for (i = 1; i < n; i++) {
if (*(p + i) > max) {
max = *(p + i);
}
if (*(p + i) < min) {
min = *(p + i);
}
}

printf("Maximum element = %d\n", max);


printf("Minimum element = %d\n", min);
return 0;
}

3. Find the maximum and minimum elements in a 1D array using pointers


#include <stdio.h>

int main() {
int arr[5], i;
int *p = arr;
int max, min;

printf("Enter 5 integers: ");


for(i = 0; i < 5; i++) {
scanf("%d", (p + i));
}

max = min = *p;

for(i = 1; i < 5; i++) {


if(*(p + i) > max) {
max = *(p + i);
}
if(*(p + i) < min) {
min = *(p + i);
}
}

printf("Maximum = %d\n", max);


printf("Minimum = %d\n", min);
return 0;
}

4. Input a 2x3 matrix and display it using pointer notation


#include <stdio.h>

int main() {
int arr[2][3], i, j;

printf("Enter elements of 2x3 matrix:\n");


for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
scanf("%d", * (arr + i) + j);
}
}

printf("Matrix is:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", *(*(arr + i) + j));
}
printf("\n");
}
return 0;
}

5. Store and print a list of 5 strings using an array of character pointers


#include <stdio.h>

int main() {
char *names[5] = {"Alice", "Bob", "Charlie", "David", "Eve"};
int i;

printf("The list of names is:\n");


for(i = 0; i < 5; i++) {
printf("%s\n", names[i]);
}
return 0;
}

You might also like