Write a C/C++ program for displaying today's date by using structure.
:: Big Index :: C/C++ Programming Tutorials ::
Thnigs you need
- computer
- programming basic
- compiler
It's a simple program to start learning structure in C/C++. This program will display today's date. Suppose today's date is 30.10.2008. So, the output of the program will be 30.10.2008.
This program is done into two ways. First program is an static initialization. In the second part (name as "Extra") the program is done by collecting values from the user.
Code of the program
#include<iostream.h>
// declaration of structure
struct date{ int day; int month; int year; };
int main(){ // object definition date today;
// initialization of members today.day = 30; today.month = 10; today.year = 2008;
// printing cout << "A program for displaying today's information"; cout << endl << endl; cout << "Today's date: "; cout << today.day << "."; cout << today.month << "."; cout << today.year << endl;
cin.get(); return 0; }
Output of the program
Discussion of the above code segment
Here 3 data (day, month and year) can be grouped together to form a structure. This group is named as "date". Definition of the "date" structure is done by the following lines:
// declaration of structure
struct date{ int day; int month; int year; };
Day, month and year - all of them are the members of this structure.
In the "main()" function, the structure object is defined. It looks:
date today;
Later, the members are initialized. Initialization looks:
today.day = 30; today.month = 10; today.year = 2008;
At last, the information is displayed by using the "cout". There is "return 0" at the end of the program because here main is integer type.
Extra
Members in an structure can be initialized without statically. The above program is implemented in anther way. Here, all the values are initialized by the user. No static initialization. The user will provide all the information and then it will display the entered information.
Modified version of the above program
#include<iostream.h>
// declearation of structure
struct date{ int day; int month; int year; };
int main(){ // object defination date today;
cout << "A program for displaying today's information"; cout << endl;
// collecting values from the user cout << "Day :"; cin >> today.day; cout << "Month:"; cin >> today.month; cout << "Year :"; cin >> today.year;
cin.get(); return 0; }