Structures and Functions
Lesson 5 of 8 in Coddy's C/C++ Structures course.
Once you create a structure in the C/C++ file, you can use this structure as a function argument or as a returned value type.
For example, let's assume Person is a structure:
void greet(Person p) {
cout << "Hello, " << p.name << endl;
}In C, you need to add the struct keyword before:
void greet(struct Person p) {
printf("Hello, %s\n", p.name);
}Challenge
EasyYou are given part of the code that creates a Point structure, initializes two points, and calculates the distance between them.
Your task is to create a function named calcDistance that gets two Point structures as arguments, calculates the distance and returns it (int type).
Given two points p1 and p2 the distance between them is:
(p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)You don't need to modify the main function at all!
Try it yourself
#include <stdio.h>
struct Point {
int x;
int y;
};
// Implement calcDistance here
int main() {
char tmp[50];
int p1x, p1y, p2x, p2y;
scanf("%s %d %d", &tmp, &p1x, &p1y);
scanf("%s %d %d", &tmp, &p2x, &p2y);
struct Point p1 = {p1x, p1y};
struct Point p2 = {p2x, p2y};
int distance = calcDistance(p1, p2);
printf("Distance between p1 and p2: %d", distance);
return 0;
};