Structure Assignment 7 — Create a Structure to Represent a Point in 2D Space
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Create a Structure to Represent a Point in 2D Space (x, y)

šŸ“‘ On this page:
  • A point is just two numbers
  • The struct and its two floats
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
šŸ“š In this program, you will learn:
  • How to model a 2D point with a small struct — two floats, x and y
  • Why we use float for coordinates, not int
  • How to print a point so it looks like a coordinate pair, (x, y)
  • How to keep several points in an array so you can print a list
  • How this little struct becomes the building block for distance, midpoint, and line calculations

A point is just two numbers

On a 2D plane, a point is nothing more than an x-coordinate and a y-coordinate. That's it. You could keep them in two separate variables — float x1 = 2.5, y1 = 3.1; — and for a single point, that's fine. But the moment you have two points, you have four variables, and if you have ten points, you have twenty. Every time you pass them to a function, you pass four arguments. Every time you copy a point, you copy two variables. It gets messy.

A struct says "a point is a pair of floats, and they travel together". So struct point p; is a single variable holding both numbers. Passing a point means passing one argument. Copying a point means one assignment. Printing a point means one call, not two. The struct is small — just two floats — but the idea is big: you're inventing a new type that matches how you think about the problem.

This is also the first assignment in the series where the struct has no strings at all. That makes the code noticeably shorter — no strcpy, no char[] buffers — and focuses attention on the numeric side. It's a good place to get comfortable with the basics: define, declare, fill, print. Everything else in this category — distance between two points, midpoint, whether three points are collinear — builds on this little struct.

šŸ’” In one line: struct point { float x; float y; }; is a new type. struct point p = {2.5f, 3.1f}; creates one point. p.x and p.y are the two numbers.

A small graph with two points labelled P1 at (2.5, 3.1) and P2 at (-1.0, 4.5). Each point is drawn as a dot with dashed lines down to the x-axis and across to the y-axis.

The struct and its two floats

The struct is about as small as structs get:

struct point {
    float x;
    float y;
};
                                

Two members, both floats. No arrays, no strings, no nested structs. The semicolon after the closing brace is still required, same as always.

Member Type Meaning Example
xfloatHorizontal positionp.x = 2.5f;
yfloatVertical positionp.y = 3.1f;

Why float and not int? Because points rarely sit neatly on whole numbers. A point at (2.5, 3.1) is a perfectly valid position on the plane. If you used int, you'd only be able to represent points on the integer grid, and every calculation that produced a fractional result (midpoint, intersection) would get chopped. For graphics, physics, or any real geometry, you want floating point.

Complete C Program

Program: define and print a couple of points

#include <stdio.h>

struct point {
    float x;
    float y;
};

int main(void) {
    struct point p1 = {2.5f, 3.1f};
    struct point p2 = {-1.0f, 4.5f};

    printf("Point P1: (%.2f, %.2f)\n", p1.x, p1.y);
    printf("Point P2: (%.2f, %.2f)\n", p2.x, p2.y);

    return 0;
}
                                    

And here's a version that holds several points in an array, so you can see how the struct scales up to a list:

Variant: a small list of points

#include <stdio.h>

struct point {
    float x;
    float y;
};

int main(void) {
    struct point pts[4] = {
        {2.5f, 3.1f},
        {-1.0f, 4.5f},
        {0.0f, 0.0f},
        {7.8f, -2.2f}
    };

    int count = sizeof(pts) / sizeof(pts[0]);
    for (int i = 0; i < count; i++) {
        printf("P%d = (%.2f, %.2f)\n", i + 1, pts[i].x, pts[i].y);
    }

    return 0;
}
                                    

The first version is what the assignment asks for — just define the struct and show a couple of points. The second shows the same struct in an array, which is how you'd actually use it in a program with many points. Both compile with any C compiler and both print nice coordinate pairs.

Program Output

Point P1: (2.50, 3.10)
Point P2: (-1.00, 4.50)
                                

And for the array version:

P1 = (2.50, 3.10)
P2 = (-1.00, 4.50)
P3 = (0.00, 0.00)
P4 = (7.80, -2.20)
                                

Try changing the coordinates and re-running. Try negative numbers, decimals, and zero. The printing stays the same; only the numbers change. If you use the array version and change the array size, you'll need to change the initializer list to match — but the loop over the array adapts automatically.

Step-by-Step Explanation

This is one of the shortest programs in the series, so let's walk through the parts that matter.

1. The struct

struct point { float x; float y; }; — a tiny struct. Two floats, one for each coordinate. This is the entire definition of "a point" in this program. Nothing else is needed.

2. Declaring points

struct point p1 = {2.5f, 3.1f}; creates one point with x = 2.5 and y = 3.1. The braces fill x first, then y, matching the order in the struct. If you write struct point p1; without braces, you'd then need to set the fields individually: p1.x = 2.5f; p1.y = 3.1f;.

3. The little f after the numbers

2.5f is a float. Without the f, 2.5 is a double — a slightly bigger type with more precision. Assigning a double to a float field works, but the compiler converts it down and might warn if you have strict warnings on. Adding the f says "yes, I mean a float" and keeps everything consistent.

4. Printing a point

printf("(%.2f, %.2f)\n", p1.x, p1.y); prints the two members with two decimal places, wrapped in parentheses and separated by a comma. The parentheses and comma are just formatting — you could print them as 2.50 3.10 and it would still be correct — but the (x, y) form is the standard way to write coordinates, and it reads naturally.

5. The array version

struct point pts[4] = { ... }; creates an array of four points. Each inner brace {2.5f, 3.1f} is one point. The outer braces hold all four. This is the same pattern as the book-collection program: an array of structs, each one filled in its own braces. The loop then walks through and prints each one.

6. Why this little struct matters

This tiny struct is the building block for everything else in the 2D-points category. Once you have struct point, you can write a function float distance(struct point a, struct point b) that computes the distance between two points using the Pythagorean theorem. You can write struct point midpoint(struct point a, struct point b). You can check if three points are collinear. All of them take this same two-float struct and do arithmetic on the members. The distance program in the next assignment is exactly this.

7. What about int coordinates?

If your points are always on the integer grid — say, chessboard squares — you could use int x, y instead. That's fine. But most geometric calculations produce fractional results even if the inputs are whole numbers: the midpoint of (1, 2) and (2, 3) is (1.5, 2.5), which isn't representable in ints. So if there's any chance the results will be fractional, you want floats from the start. It's easier to use float consistently than to switch types in the middle of a calculation.

šŸŽÆ Remember this: a point is two floats, x and y. Use struct point p = {2.5f, 3.1f}; to create one. Print with printf("(%.2f, %.2f)\n", p.x, p.y); for the (x, y) format. Arrays of points work the same way as arrays of any other struct.

Frequently Asked Questions

1. Why floats and not ints for x and y?

Because points are rarely on whole numbers, and geometric calculations almost always produce fractional results. Even if you start with integer points, the midpoint or the distance will have decimals. Using float from the start means you don't have to worry about truncating results in the middle of a calculation. For integer-only geometry, int works — but you have to be careful every step of the way.

2. What does the f in 2.5f do?

It says "this is a float literal, not a double". Without the f, C would treat 2.5 as a double, which is a larger type. Assigning it to a float field works, but some compilers warn about the implicit conversion. Adding the f keeps everything consistent and warning-free.

3. Can I have a point with three coordinates?

Yes — just add a float z member. That's how 3D points are modelled, and the rest of the code is the same. The distance formula changes (from √((xā‚‚āˆ’x₁)² + (yā‚‚āˆ’y₁)²) to √((xā‚‚āˆ’x₁)² + (yā‚‚āˆ’y₁)² + (zā‚‚āˆ’z₁)²)) but the struct and the printing pattern stay the same. For 4D and beyond, the idea extends similarly. This is one of the nice things about structs: adding a field is a small, local change.

4. What is the size of struct point?

On most systems, 8 bytes — two 4-byte floats. There's no padding needed because both members are the same size and alignment. But don't rely on that — always use sizeof(struct point) if you need the size for something (like reading from a file or comparing). The size is a platform detail, not something you should hardcode.

5. How would I print all points in the array without hardcoding the count?

Use the same size trick as before: int count = sizeof(pts) / sizeof(pts[0]);. That gives you the number of points. Then loop for (int i = 0; i < count; i++). If you change the array from 4 points to 10, the count updates automatically and the loop still works.

6. How does this relate to the distance program?

The distance program (next in this series) takes two struct point values and computes the Euclidean distance between them: sqrt((b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)). That's it. It uses the same struct, the same fields, the same dot access. The only thing new is the sqrt call from <math.h>. If you're comfortable with this assignment, the distance one is a small step.

šŸ’” Tip: After this, try adding a char label[10] member so each point has a name like "A" or "P1". Then print A = (2.50, 3.10) instead of just the numbers. That's a small change that makes the output friendlier, and it's the exact pattern you'll use for the distance program and beyond.

šŸ“– Related Tutorials

  • 8. Initialize and Display the Coordinates of a Point Using a Structure
  • 9. Find the Distance Between Two Points Using a Structure
  • 6. Find the Total Price of a Collection of Books Using a Structure
  • Introduction to Structures in C
  • Defining a Structure
  • Accessing Structure Members
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 6. Find the Total Price of a Collection of Books Using a Structure   ||   Next Topic: -->> 8. Initialize and Display the Coordinates of a Point Using a Structure


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.