The document discusses pointers in C programming through examples of pointer arithmetic, passing pointers to functions, swapping values using and not using pointers, and finding the sum of elements in an array using pointers.
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 ratings0% found this document useful (0 votes)
5 views
Pointers
The document discusses pointers in C programming through examples of pointer arithmetic, passing pointers to functions, swapping values using and not using pointers, and finding the sum of elements in an array using pointers.
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/ 4
AIM: Pointers
1.Write programs to demonstrate the usage of pointers (pointer arithmetic,
passing pointers to functions). Code: #include <stdio.h> int doubleArray(int *a, int n) { for (int i=0;i<n;i++) { *(a+i)*=2; } } int main() { printf("For Pointer Arithmetic..\n"); int numbers[] = {1, 2, 3, 4, 5}; int *ptr = numbers;
printf("Original array: ");
for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } printf("\n"); printf("Array elements using pointers: "); for (int i = 0; i < 5; i++) { printf("%d ", *(ptr + i)); } printf("\n\n"); printf("For Pointer Passing to array...\n"); int number[] = {1, 2, 3, 4, 5}; int n = sizeof(numbers) / sizeof(number[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) { printf("%d ", number[i]); } printf("\n"); doubleArray(number, n); printf("Array after doubling elements: "); for (int i = 0; i < n; i++) { printf("%d ", number[i]); } printf("\n"); }
Output:
2. Implement functions to swap values using pointers and without using
pointers. Code: #include <stdio.h> int swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } int main() { printf("By Using Pointers:-\n"); int a = 10, b = 20; printf("Before swap: a=%d, b=%d\n",a,b); swap(&a, &b); printf("After swap: a=%d, b=%d\n", a,b); printf("\nBy Not Using Pointer:-\n"); printf("Before swap: a=%d, b=%d\n",a,b); a=a+b; b=a-b; a=a-b; printf("After swap: a=%d, b=%d\n", a, b); return 0; } Output:
3.Create a program to find the sum of elements in an array using pointers.
Code: #include<stdio.h> int main() { int n,i,s; printf("Enter the size of array: "); scanf("%d",&n); int a[n]; printf("Enter the %d elements of array: ",n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("["); for(s=0;s<i-1;s++) { printf("%d, ",a[s]); } for(s=i-1;s<i;s++) { printf("%d",a[s]); } printf("]"); //sum of elements int sum=0; for(int d=0;d<s;d++) { sum=sum+a[d]; } printf("\nThe sum of elemenys in array is %d\n",sum); return 0; } Output: