About Lesson
Program1: Pointer Usage Example
#include <stdio.h>#include <conio.h>void main(){// Declare and initialize a float variablefloat x = 10;// Declare a pointer to floatfloat *ptr;// Print the value of xprintf(“nX=%f”, x);// Print the address of x using the address-of operator (&)printf(“nAddress of X=%u”, &x);// Use the Value At Address operator (*) to get the value at the address of xprintf(“nX=%f”, *&x);// Assign the address of x to the pointer variable ptrptr = &x;// Print the address stored in the pointer variable ptrprintf(“nAddress of X=%u”, ptr);// Print the value at the address stored in the pointer variable ptrprintf(“nValue of X=%f”, *ptr);// Modify the value at the address stored in the pointer variable ptr*ptr = 100;// Print the modified value of xprintf(“nValue of X=%f”, x);// Wait for a key press before closing the console windowgetch();}
Output:
X=10.000000
Address of X=245364804
X=10.000000
Address of X=245364804
Value of X=10.000000
Value of X=100.000000
Program2: C program that uses pointers to swap the values of two integers.
#include <stdio.h>// Function to swap the values of two integers using pointersvoid swap(int *a, int *b){int temp = *a; // Store the value at the address pointed by ‘a’ in a temporary variable*a = *b; // Assign the value at the address pointed by ‘b’ to the address pointed by ‘a’*b = temp; // Assign the value stored in the temporary variable to the address pointed by ‘b’}int main(){int num1 = 5, num2 = 10;// Print the initial valuesprintf(“Before swapping: num1 = %d, num2 = %dn”, num1, num2);// Call the swap function with the addresses of num1 and num2swap(&num1, &num2);// Print the values after swappingprintf(“After swapping: num1 = %d, num2 = %dn”, num1, num2);return 0;}
Output:
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5
Program3: program that uses pointers to find the sum of elements in an array.
#include <stdio.h>// Function to find the sum of elements in an arrayint findSum(int *arr, int size){int sum = 0;// Loop through each element of the array using a pointerfor (int i = 0; i < size; i++){sum += *(arr + i); // Access each element using pointer arithmetic}return sum; // Return the calculated sum}int main(){// Declare an array of integersint numbers[] = {1, 2, 3, 4, 5};int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array// Print the elements of the arrayprintf(“Array elements: “);for (int i = 0; i < size; i++){printf(“%d “, numbers[i]);}// Call the findSum function to calculate the sum of array elementsint result = findSum(numbers, size);// Print the sum of array elementsprintf(“nSum of array elements: %dn”, result);return 0;}
Output:
Array elements: 1 2 3 4 5
Sum of array elements: 15