C Exercise Example 78
Title:Find the person with the greatest age and output it. Please identify what issues exist in the program.
Program analysis:None.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
// Define a structure type to store a person's name and age
struct man {
char name[20];
int age;
} person[3] = {{"li", 18}, {"wang", 25}, {"sun", 22}}; // Initialize the array
int main() {
struct man *q = NULL; // Used to point to the person with the maximum age
struct man *p = person; // Point to the starting address of the array
int i;
int max_age = 0; // Store the maximum age
// Traverse the array to find the oldest person
for (i = 0; i < 3; i++) {
if (p->age > max_age) { // If the current age is greater than max_age
max_age = p->age; // Update max_age
q = p; // Point q to the current person
}
p++; // Move to the next person
}
// Output the name and age of the oldest person
if (q != NULL) {
printf("%s %d\n", q->name, q->age);
} else {
printf("No person information found.\n");
}
return 0;
}
The output result of running the above example is:
wang 25other extensions