0% found this document useful (0 votes)
23 views19 pages

POINTERS and STRUCTURES Programs

Uploaded by

lawrencemelphine
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)
23 views19 pages

POINTERS and STRUCTURES Programs

Uploaded by

lawrencemelphine
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/ 19

POINTERS

C programming exercises: Pointer - w3resource


Check the above link for programming exercises

1. Dynamic Memory Allocation with malloc()


This program dynamically allocates memory for an integer array and initializes its values.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
// Check if memory was allocated successfully
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input values into the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the values
printf("The entered values are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}

2. Dynamic Memory Allocation with calloc()


This program allocates memory for an array of integers using calloc(), which initializes the
memory to zero.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n integers and initialize to 0
arr = (int *)calloc(n, sizeof(int));
// Check if memory was allocated successfully
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Display the initialized values
printf("The array values after calloc initialization are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}
3. Dynamic Memory Allocation with realloc()
This program shows how to change the size of the dynamically allocated memory using
realloc().
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;

printf("Enter the initial number of elements: ");


scanf("%d", &n);
// Dynamically allocate memory for n integers
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input values into the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Display the values
printf("Entered values are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Reallocate memory to hold more integers
printf("\nEnter the new size: ");
scanf("%d", &n);
arr = (int *)realloc(arr, n * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}
// Input new values
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Display the updated array


printf("The updated values are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}
4. Dynamic Memory Allocation for 2D Array
This program dynamically allocates memory for a 2D array using pointers.
#include <stdio.h>
#include <stdlib.h>
int main() {
int **arr, rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Dynamically allocate memory for rows pointers
arr = (int **)malloc(rows * sizeof(int *));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Dynamically allocate memory for columns for each row
for (int i = 0; i < rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
if (arr[i] == NULL) {
printf("Memory allocation failed for row %d!\n", i);
return 1;
}
}

// Input values into the 2D array


printf("Enter values for the 2D array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &arr[i][j]);
}
}
// Display the 2D array
printf("The 2D array values are:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

// Free the allocated memory


for (int i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);

return 0;
}

1. Program to Swap Two Numbers Using Pointers


#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int *x, *y;
x = (int *)malloc(sizeof(int));
y = (int *)malloc(sizeof(int));
if (x == NULL || y == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter two integers: ");
scanf("%d %d", x, y);
printf("Before swap: x = %d, y = %d\n", *x, *y);
swap(x, y);
printf("After swap: x = %d, y = %d\n", *x, *y);
free(x);
free(y);
return 0;
}
Sample Output:
Enter two integers: 5 10
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
2. Program to Find the Length of a String Using Pointers
#include <stdio.h>
#include <stdlib.h>
int stringLength(char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}

int main() {
char *str;
str = (char *)malloc(100 * sizeof(char));
if (str == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter a string: ");
fgets(str, 100, stdin);
int length = stringLength(str);
printf("Length of the string is: %d\n", length);
free(str);
return 0;
}
Sample Output:
Enter a string: Hello, world!
Length of the string is: 13
3. Program to Add Two Matrices Using Pointers
#include <stdio.h>
#include <stdlib.h>
int main() {
int **matrix1, **matrix2, **sum;
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Allocate memory for matrices
matrix1 = (int **)malloc(rows * sizeof(int *));
matrix2 = (int **)malloc(rows * sizeof(int *));
sum = (int **)malloc(rows * sizeof(int *));

for (int i = 0; i < rows; i++) {


matrix1[i] = (int *)malloc(cols * sizeof(int));
matrix2[i] = (int *)malloc(cols * sizeof(int));
sum[i] = (int *)malloc(cols * sizeof(int));
}
// Input matrix1
printf("Enter elements of matrix1:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input matrix2
printf("Enter elements of matrix2:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix2[i][j]);
}
}
// Add matrices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display sum matrix
printf("Sum of the matrices:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}

// Free memory
for (int i = 0; i < rows; i++) {
free(matrix1[i]);
free(matrix2[i]);
free(sum[i]);
}
free(matrix1);
free(matrix2);
free(sum);

return 0;
}
Sample Output:
Enter the number of rows and columns: 2 2
Enter elements of matrix1:
12
34
Enter elements of matrix2:
56
78
Sum of the matrices:
68
10 12
4. Program to Reverse an Array Using Pointers
#include <stdio.h>
#include <stdlib.h>
void reverseArray(int *arr, int size) {
int *start = arr;
int *end = arr + size - 1;
int temp;

while (start < end) {


temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
int *arr, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for the array
arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input values into the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Reverse the array
reverseArray(arr, n);
// Display the reversed array
printf("Reversed array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Free the allocated memory


free(arr);

return 0;
}
Sample Output:
Enter the number of elements: 5
Enter 5 integers:
12345
Reversed array:
54321
5. Program to Calculate the Sum of an Array Using Pointers
#include <stdio.h>
#include <stdlib.h>
int sumArray(int *arr, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += *(arr + i);
}
return sum;
}

int main() {
int *arr, n;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for the array
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input values into the array
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Calculate and display the sum
int sum = sumArray(arr, n);
printf("Sum of the array elements is: %d\n", sum);
// Free the allocated memory
free(arr);
return 0;
}
Sample Output:
Enter the number of elements: 4
Enter 4 integers:
1234
Sum of the array elements is: 10

STRUCTURES
1. Program to Store and Display Student Information
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int roll_no;
float marks;
};

int main() {
struct Student student;
// Input student details
printf("Enter student's name: ");
fgets(student.name, sizeof(student.name), stdin);
printf("Enter roll number: ");
scanf("%d", &student.roll_no);
printf("Enter marks: ");
scanf("%f", &student.marks);
// Display student details
printf("\nStudent Information:\n");
printf("Name: %s", student.name);
printf("Roll Number: %d\n", student.roll_no);
printf("Marks: %.2f\n", student.marks);
return 0;
}
Sample Output:
Enter student's name: John Doe
Enter roll number: 101
Enter marks: 85.5
Student Information:
Name: John Doe
Roll Number: 101
Marks: 85.50
2. Program to Calculate Area of a Rectangle Using Structures
#include <stdio.h>
struct Rectangle {
float length;
float width;
};
float calculateArea(struct Rectangle rect) {
return rect.length * rect.width;
}
int main() {
struct Rectangle rect;
// Input rectangle dimensions
printf("Enter length of the rectangle: ");
scanf("%f", &rect.length);
printf("Enter width of the rectangle: ");
scanf("%f", &rect.width);
// Calculate and display area
float area = calculateArea(rect);
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
Sample Output:
Enter length of the rectangle: 5.5
Enter width of the rectangle: 4.2
The area of the rectangle is: 23.10
3. Program to Store and Display Date Using Structure
#include <stdio.h>
struct Date {
int day;
int month;
int year;
};
int main() {
struct Date date;
// Input date details
printf("Enter day: ");
scanf("%d", &date.day);
printf("Enter month: ");
scanf("%d", &date.month);
printf("Enter year: ");
scanf("%d", &date.year);
// Display date
printf("\nEntered date is: %02d/%02d/%d\n", date.day, date.month, date.year);
return 0;
}
Sample Output:
Enter day: 25
Enter month: 12
Enter year: 2024
Entered date is: 25/12/2024
4. Program to Store and Display Employee Information
#include <stdio.h>
struct Employee {
char name[50];
int id;
float salary;
};
int main() {
struct Employee emp;
// Input employee details
printf("Enter employee name: ");
fgets(emp.name, sizeof(emp.name), stdin);
printf("Enter employee ID: ");
scanf("%d", &emp.id);
printf("Enter employee salary: ");
scanf("%f", &emp.salary);
// Display employee details
printf("\nEmployee Information:\n");
printf("Name: %s", emp.name);
printf("ID: %d\n", emp.id);
printf("Salary: %.2f\n", emp.salary);
return 0;
}
Sample Output:
Enter employee name: Alice Smith
Enter employee ID: 12345
Enter employee salary: 55000.75
Employee Information:
Name: Alice Smith
ID: 12345
Salary: 55000.75
5. Program to Add Two Complex Numbers Using Structures
#include <stdio.h>
struct Complex {
float real;
float imag;
};
struct Complex addComplex(struct Complex c1, struct Complex c2) {
struct Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
int main() {
struct Complex c1, c2, sum;
// Input complex numbers
printf("Enter real and imaginary parts of first complex number: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter real and imaginary parts of second complex number: ");
scanf("%f %f", &c2.real, &c2.imag);
// Add complex numbers
sum = addComplex(c1, c2);
// Display the sum
printf("Sum of the complex numbers: %.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
Sample Output:
Enter real and imaginary parts of first complex number: 3.5 4.2
Enter real and imaginary parts of second complex number: 1.2 2.3
Sum of the complex numbers: 4.70 + 6.50i
6. Program to Find Largest of Three Numbers Using Structures
#include <stdio.h>
struct Numbers {
int num1;
int num2;
int num3;
};
int findLargest(struct Numbers n) {
if (n.num1 >= n.num2 && n.num1 >= n.num3) {
return n.num1;
} else if (n.num2 >= n.num1 && n.num2 >= n.num3) {
return n.num2;
} else {
return n.num3;
}
}
int main() {
struct Numbers n;
// Input three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &n.num1, &n.num2, &n.num3);
// Find and display the largest number
int largest = findLargest(n);
printf("The largest number is: %d\n", largest);
return 0;
}
Sample Output:
Enter three numbers: 10 25 15
The largest number is: 25
7. Program to Calculate Simple Interest Using Structure
#include <stdio.h>
struct SimpleInterest {
float principal;
float rate;
float time;
};
float calculateInterest(struct SimpleInterest si) {
return (si.principal * si.rate * si.time) / 100;
}
int main() {
struct SimpleInterest si;
// Input values
printf("Enter principal: ");
scanf("%f", &si.principal);
printf("Enter rate of interest: ");
scanf("%f", &si.rate);
printf("Enter time period: ");
scanf("%f", &si.time);
// Calculate and display simple interest
float interest = calculateInterest(si);
printf("Simple Interest: %.2f\n", interest);
return 0;
}
Sample Output:
Enter principal: 5000
Enter rate of interest: 5
Enter time period: 2
Simple Interest: 500.00

You might also like