# Write a trigger to create N number of child Contact records based on the value specified in the Number_of_Locations__c field on Account.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Cognizant, TCS, Mindtree · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-create-n-number-of-child-contact-records-based-on-the-value-specified-in-the-number-of

## Answer

Use `after insert` (Ids needed for the parent link) and create N child Contacts per Account.

```apex
trigger AccountTrigger on Account (after insert) {
    List<Contact> cons = new List<Contact>();
    for (Account a : Trigger.new) {
        Integer n = a.Number_of_Locations__c == null ? 0 : (Integer) a.Number_of_Locations__c;
        for (Integer i = 1; i <= n; i++) {
            cons.add(new Contact(LastName = a.Name + ' Location ' + i, AccountId = a.Id));
        }
    }
    if (!cons.isEmpty()) insert cons;
}
```
Watch the 10,000 DML row limit if the number is large.

---
Source: ForceChallenges · last updated 2026-10-19
