Menu
Coddy logo textTech

Project: Define Contact Struct

Part of the Logic & Flow section of Coddy's C journey — lesson 50 of 63.

challenge icon

Challenge

Easy

You'll be building a simple contact entry tool that demonstrates how structs can organize related data in real-world applications.

Create a C program that defines a Contact struct to store contact information. Your program should:

  1. Define a struct named Contact with the following members:
    • A character array name with size 50 to store the contact's name
    • A character array phone with size 20 to store the contact's phone number
    • A character array email with size 40 to store the contact's email address
    • An integer age to store the contact's age
  2. In the main function:
    • Create a Contact variable named person
    • Read the following input values and assign them to the struct members using the dot operator:
      • Read a string for the name and assign it to person.name
      • Read a string for the phone number and assign it to person.phone
      • Read a string for the email and assign it to person.email
      • Read an integer for the age and assign it to person.age
    • After reading all values, perform the following validation checks:
      • If the age is less than 0 or greater than 120, print Invalid age and exit the program
      • If the phone number length is less than 10 characters, print Invalid phone number and exit the program
    • If all validations pass, print the contact information in this exact format:
      • Contact Information:
      • Name: [name]
      • Phone: [phone]
      • Email: [email]
      • Age: [age]
    • Calculate and print additional information:
      • Print the length of the name using strlen() in the format: Name length: [length]
      • Determine the age category and print it:
        • If age is between 0 and 17: Category: Minor
        • If age is between 18 and 64: Category: Adult
        • If age is 65 or above: Category: Senior

This challenge tests your understanding of struct definition, member declaration with appropriate data types and sizes, accessing struct members using the dot operator, input validation, and using string functions like strlen() with struct members. You'll practice creating a practical data structure that could serve as the foundation for a contact management system.

Try it yourself

#include <stdio.h>
#include <string.h>

// TODO: Define the Contact struct here

int main() {
    // TODO: Create a Contact variable named person
    
    // Read input values
    scanf("%s", /* TODO: assign to person.name */);
    scanf("%s", /* TODO: assign to person.phone */);
    scanf("%s", /* TODO: assign to person.email */);
    scanf("%d", /* TODO: assign to person.age */);
    
    // TODO: Write your validation and output code below
    
    return 0;
}

All lessons in Logic & Flow