Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Write a c program to find age of a person ?

Here’s a simple C program that asks the user for their birth year and calculates their current age based on the current year:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int birth_year, current_year, age;
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);
    current_year = tm.tm_year + 1900;

    printf("Enter your birth year: ");
    scanf("%d", &birth_year);

    age = current_year - birth_year;
    printf("Your age is %d\n", age);

    return 0;
}

Explanation:

  • We first declare three integer variables: birth_year, current_year, and age.
  • We then use the time function to get the current time in seconds since the Unix epoch (January 1, 1970), and store it in the t variable.
  • We use the localtime function to convert the current time from seconds to a struct tm object, which contains various time-related fields such as year, month, day, etc. We store this in the tm variable.
  • We set current_year to tm.tm_year + 1900, since the tm_year field in the struct tm object represents the number of years since 1900.
  • We prompt the user to enter their birth year using the printf and scanf functions.
  • We calculate the age by subtracting the birth year from the current year, and store it in the age variable.
  • We use the printf function to display the age to the user.

Note: This program assumes that the user inputs their birth year correctly as an integer. It does not perform any input validation or error checking.