Explanation
The program prints the name and age entered by the user using a function.
Header
The code begins with including the standard input-output header file and string manipulation header file using #include <stdio.h>
and #include <string.h>
.
Function Declaration
The program declares a function printNameAndAge
to print the name and age:
void printNameAndAge(char *name, int age);
: Declares the function with a character pointername
and an integerage
as parameters.
Variable Declaration
The main()
function is defined, and two variables are declared:
char name[100]
: Array to hold the user's name.int age
: Variable to hold the user's age.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter their name and age:
printf("Enter your name: ");
: Prompts the user to enter their name.fgets(name, sizeof(name), stdin);
: Reads the name including spaces and stores it in the arrayname
.name[strcspn(name, "\n")] = 0;
: Removes the newline character from the end of the name.printf("Enter your age: ");
: Prompts the user to enter their age.scanf("%d", &age);
: Reads the age and stores it inage
.
Function Call
The program calls the printNameAndAge
function to print the name and age:
printNameAndAge(name, age);
: Calls the function withname
andage
as arguments.
Function Definition
The program defines the printNameAndAge
function:
void printNameAndAge(char *name, int age)
: Defines the function with a character pointername
and an integerage
as parameters.printf("Your name is %s and your age is %d years.\n", name, age);
: Prints the name and age.
Program End
The program ends with return 0;
to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
void printNameAndAge();
int main()
{
printf("\n\n Program to print name and age entered by the user using function. \n\n");
char name[100];
int age;
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = 0;
printf("Enter your age: ");
scanf("%d", &age);
printNameAndAge(name, age);
return 0;
}
void printNameAndAge(char *name, int age)
{
printf("Your name is %s and your age is %d years.\n", name, age);
}
Output
Program to print name and age entered by the user using function.
Enter your name: dmj.one
Enter your age: 11
Your name is dmj.one and your age is 11 years.