Name: SAMI HAFIZ AL STUDENT ID: 2411604115
Class: Computer Science Class-1
Fundamental of Programming: POINTER Codes
Exercise 1: Use Pointers to Calculate Highest, Lowest, and
Average of Three Values
#include <stdio.h>
void pointerStats(int v1, int v2, int v3, int *highest, int *lowest,
float *mean) {
*highest = v1;
if (v2 > *highest) *highest = v2;
if (v3 > *highest) *highest = v3;
*lowest = v1;
if (v2 < *lowest) *lowest = v2;
if (v3 < *lowest) *lowest = v3;
*mean = (v1 + v2 + v3) / 3.0;
}
int main() {
int p, q, r, hi, lo;
float avg;
printf("Input three integers: ");
scanf("%d %d %d", &p, &q, &r);
pointerStats(p, q, r, &hi, &lo, &avg);
printf("Max=%d Min=%d Mean=%.2f\n", hi, lo, avg);
return 0;
}
Exercise 2: Convert Minutes to Hours and Minutes Using Pointers
#include <stdio.h>
void convert(int mins, int *hrs, int *m) {
*hrs = mins / 60;
*m = mins % 60;
}
int main() {
int mins, hours, left;
printf("Minutes: ");
scanf("%d", &mins);
convert(mins, &hours, &left);
printf("%d min = %d hour(s) %d min\n", mins, hours, left);
return 0;
}
Exercise 3: Perform Calculations with Function Pointers
#include <stdio.h>
typedef float (*operation)(float, float);
float add(float x, float y) { return x + y; }
float sub(float x, float y) { return x - y; }
float mul(float x, float y) { return x * y; }
float div(float x, float y) { return y ? x / y : 0; }
int main() {
operation ops[4] = {add, sub, mul, div};
char *labels[] = {"Plus", "Minus", "Times", "Divide"};
float v = 12, w = 4;
for (int i = 0; i < 4; i++)
printf("%s: %.2f\n", labels[i], ops[i](v, w));
return 0;
}
Exercise 4: Calculate Area and Perimeter Using Function Pointers
in Struct
#include <stdio.h>
#define PI 3.14159
typedef struct {
double (*area)(double, double);
double (*perim)(double, double);
} Figure;
double circA(double r, double _) { return PI * r * r; }
double circP(double r, double _) { return 2 * PI * r; }
double rectA(double l, double w) { return l * w; }
double rectP(double l, double w) { return 2 * (l + w); }
int main() {
Figure fig;
int sel;
double m, n;
printf("Choose (1)Circle or (2)Rectangle: ");
scanf("%d", &sel);
if (sel == 1) {
[Link] = circA; [Link] = circP;
printf("Radius: "); scanf("%lf", &m); n = 0;
} else {
[Link] = rectA; [Link] = rectP;
printf("Len & Wid: "); scanf("%lf%lf", &m, &n);
}
printf("Area=%.2f Perimeter=%.2f\n", [Link](m, n), [Link](m,
n));
return 0;
}
Exercise 5: Print a String Character by Character Using a Pointer
#include <stdio.h>
int main() {
char txt[] = "Pointer";
char *pt = txt;
while (*pt) {
printf("%c", *pt);
pt++;
}
printf("\n");
return 0;
}
Exercise 6: Sort and Display a List of Strings Using Pointers
#include <stdio.h>
#include <string.h>
int main() {
char *arr[] = { "Apple", "Banana", "Lime", "Cherry", "Peach" };
int cnt = 5;
for (int i = 0; i < cnt - 1; i++) {
for (int j = i + 1; j < cnt; j++) {
if (strcmp(arr[i], arr[j]) > 0) {
char *temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < cnt; i++) printf("%s\n", arr[i]);
return 0;
}