Step-by-step Code Creation in C++

Follow the steps to solve a problem, gradually expanding the code.

The problem here will be to create a program which will tell what day of the week a particular date is or was, in various years.

The user will enter the date in the form of 7 29 1999 for July 29, 1999.
The program should respond: July 29, 1999 falls on a Thursday.
Where do we start?

First there some rules we must be aware of that will figure into our program.

Rules

1. A year has 365 days(see rule 4 & 6 for exceptions).
2. There are tweleve months in a year.
3. There are seven days in the week.
4. Every fourth year is a leapyear(one day is added making the year 366 days long),
specifically years divisible evenly by 4(i.e., 1984).
5. Years divisible evenly by 100 are not leap years (i.e., 1900: not a leapyear, 1904: a leapyear).
6. Years divisible evenly by 400 do not follow rule 5(i.e., 1800: not a leapyear, 2000: a leapyear).
7. The tweleve months have these numbers of days:
        January 30
        February 28(see rule 8 for exception)
        March 31
        April 30
        May 31
        June 30
        July 31
        August 31
        September 30
        October 31
        November 30
        December 31
8. In a leapyear February has 29 Days. 9. The first day of each year(January 1) falls on the following
week day of the first day of the previous year(i.e., Jan 1, 1900: Monday,
Jan 1, 1901: Tuesday), except for years following leapyears.


Wow! How do we fit all that into a program?
It is easy to fall into the programming trap of trying to do it all at once and trying to write all the code right-away. This never works. Code is generated in stages. The first stage requires writing an algorithm. An algorithm is a plan of attack, a list of problems that need to be solved and their possible solutions. The Rules list above is part of our algorithm, and we'll attack it one step at a time.

Let's start by wrting a main() shell for our program.
#include < stdio.h >
#include < iostream.h >

int main()
{


return 0; }


This will compile without errors, but does nothing.
Within this shell we will build our program.
The first thing we want to be able to do is take in three values. Specifically, the day, month and year.
For this we need to create three int values by declaring them at the begining of the program.
#include < stdio.h >
#include < iostream.h >

int main()
{

int m, day, year; //month, day and year

return 0; }


We could have also declared these integer variables on seperate lines like this:
int m;
int day;
int year;
The first way saves space and groups them in a way that tells anyone reading the code that they are together for a reason.
Next, we need a way of assigning values to these variables. We want to be able to take user input from the keyboard. For this we will use cin >> . This is the "C-in" operator. In plain-old C it was called "scanf" for scan function, in other languages it may be called: READ, STDIN(for "standard input"). the >> indicates the direction of the information flow. >> is going into our program, << would be going out.
#include < stdio.h >
#include < iostream.h >

int main()
{

int m, day, year; //month, day and year

cin>>m>>day>>year; //Take in our three variables
return 0; }


We want to be able to ask our users for input and tell them what the program is for.
#include < stdio.h >
#include < iostream.h >

int main()
{

int m, day, year; //month, day and year

  cout<< "\nEnter any date after 1900 as three sets of numbers.\n";
  cout<< "(month, day, year). Example: 7 29 1971 for July 29, 1971\n";
  cout<<"Enter date: ";
  cin>>m>>day>>year; //Take in our three variables

return 0; }


The "\n" at the end of each line of output is called an escape character There are many such characters all start with a backslash. This one tells the C++ compiler to skip to the next line after printing the output.

We also don't want the main() function doing all of our work for us. It's sloppy programming and C++ uses better methods. We will pass our three values to a function as parameters. A function is like a program within a program that does some special work(usually calculation) and send the answer back to the main program. In C++ functions must be declared before the program starts as a way of telling the compiler, "There's a function in here!" We will also make a call to the function within our program that passes the variables(parameters) to the function. Finally, outside of our program will be the function itself. Sounds complex? Don't worry, functions and parameter passing are some of the most difficult concepts for new programmers to learn. I had written and used several functions before I grasped the concept.
#include < stdio.h >
#include < iostream.h >

int get_date(int, int, int); //Our function declaration
int main()
{

int m, day, year; //month, day and year

  cout<< "\nEnter any date after 1900 as three sets of numbers.\n";
  cout<< "(month, day, year). Example: 7 29 1971 for July 29, 1971\n";
  cout<<"Enter date: ";
  cin>>m>>day>>year; //Take in our three variables

get_date(m, day, year); //Our function call
return 0;
}


//Below is our get_date function. Does nothing yet.
int get_date(int the_m, int the_day, int the_year){



return 0;
}


Notice three important things:
1. Our function declaration is above and outside of our program with the #include headers.
2. Our call passes our three values to get_date()
3. Our get_date function is outside of the main() program in its own area.


The function does nothing right now, but we will be using it soon. The next thing we want to do is add some items to our main program. We want to be able to ask for dates repeatedly and we also want some way to end the program. In addition, we want some kind of error checking so users can't send bogus dates to our get_date() function. We will do this with a while() loop. A while() loop runs while the condition in its parentheses is true(or not false). It's like saying: "While the light is green, I can drive through the intersection." That statement could be coded as such:

while(the light is green){

drive through intersection;

}

More acuratelly:

int green = 1;
int light = green;
int red = 2;
while(light == green){
cout<<"I can drive through";
light = red;
}

This code is kind of silly, but it shows the point.
Now we can add out while() loop and condition.

#include < stdio.h >
#include < iostream.h >

int get_date(int, int, int); //Our function declaration
int main()
{

int m, day, year; //month, day and year

  cout<< "\nEnter any date after 1900 as three sets of numbers.\n";
  cout<< "(month, day, year). Example: 7 29 1971 for July 29, 1971\n";
  cout<<"Entering invalid dates will exit the program.\n";
  cout<<"Enter date: ";
  cin>>m>>day>>year; //Take in our three variables

while((m != 13)&(day !=32)&(year != 0000)){
   //Invalid dates exit the loop

   get_date(m, day, year); //Our function call
}
  cout<<"\nYou entered an invalid date! End Program!" << endl;

return 0;
}


//Below is our get_date function. Does nothing yet.
int get_date(int the_m, int the_day, int the_year){



return 0;
}
Notice the "<< endl;" This stands for "end line" it has a similar function to \n but has the added ability to clear out the memory buffer as well as skipping to the next line. Don't worry about clearing out memory buffers at this stage, it's just a good programming habit to get into.

Now, we going to make our program start doing things. We're going to add some code to our function that will tell us which month a person entered.
#include < stdio.h >
#include < iostream.h >

int get_date(int, int, int); //Our function declaration
int main()
{

int m, day, year; //month, day and year

  cout<< "\nEnter any date after 1900 as three sets of numbers.\n";
  cout<< "(month, day, year). Example: 7 29 1971 for July 29, 1971\n";
  cout<<"Entering invalid dates will exit the program.\n";
  cout<<"Enter date: ";
  cin>>m>>day>>year; //Take in our three variables

while((m != 13)&(day !=32)&(year != 0000)){
   //Invalid dates exit the loop

   get_date(m, day, year); //Our function call
}
  cout<<"\nYou entered an invalid date! End Program!" << endl;

return 0;
}


//get_date function.
int get_date(int the_m, int the_day, int the_year){

//initial values for months of the year
  int jan = 0, febr = 31, mar = 59, apr = 90,
  may = 120, june = 151, july = 181, aug = 212,
  sept = 243, octo = 273, nov = 304, dec = 334;


return 0;
}
Before we add any more code to the function, let's slow down and describe what we're doing. We have declared a set of 12 integers, each one for a month of the year. Remeber, we are trying to determine what day of the year a particular date is. We are only concerned about the number of days a month has in that context. We are going to add the value of a month(meaning the number of days that have passed before the start of the month) and the day of the month entered. If the user enters January 12, we add jan(0) to 12. jan + 12 = 12. January 12 is the 12th day of the year. If the user enters December 31. dec + 31 = 365. December 31 is the 365th day of the year.

For a while, we're just going to look at the function. The rest of our program will remain the same until we are done with the get_date function.


//get_date function(so far).
int get_date(int the_m, int the_day, int the_year){

//initial values for months of the year
  int jan = 0, febr = 31, mar = 59, apr = 90,
  may = 120, june = 151, july = 181, aug = 212,
  sept = 243, octo = 273, nov = 304, dec = 334;

  int the_month, the_date; //We need to declare some other variables for the function.

   switch(the_m){      case 3: the_month = mar; break;
     case 4: the_month = apr; break;
     case 5: the_month = may; break;
     case 6: the_month = june; break;
     case 7: the_month = july; break;
     case 8: the_month = aug; break;
     case 9: the_month = sept; break;
     case 10: the_month = octo; break;
     case 11: the_month = nov; break;
     case 12: the_month = dec; break;
   }

return 0;
}
What we have added here is called a switch() statement. The switch statement is powerfull tool for making choices in a program. The parameter is passed into the switch() statement through the parentheses. The value passed should match one of the case: values. In our situation, it's the months of the year that are the values. break; allows us to exit the switch() statement once our match has been found. Between each case: and break; our assignment takes place. This is the value that is passed out of the switch() and back to our function.
As you can see, the switch() starts with March. This is so because January and February are special and will be dealt with in different way.
//get_date function(so far).
int get_date(int the_m, int the_day, int the_year){

//initial values for months of the year
  int jan = 0, febr = 31, mar = 59, apr = 90,
  may = 120, june = 151, july = 181, aug = 212,
  sept = 243, octo = 273, nov = 304, dec = 334;

  int the_month, the_date; //Variables used in calculations

if(3 > the_m){
    if(2 == the_m){
    the_date = febr + the_day;
    }
    else{
      if(1 == the_m){
      the_date = jan + the_day;
      }
    }
    }
    else{

   switch(the_m){
     case 3: the_month = mar; break;
     case 4: the_month = apr; break;
     case 5: the_month = may; break;
     case 6: the_month = june; break;
     case 7: the_month = july; break;
     case 8: the_month = aug; break;
     case 9: the_month = sept; break;
     case 10: the_month = octo; break;
     case 11: the_month = nov; break;
     case 12: the_month = dec; break;
   }
 }

return 0;
}
We have now added a nested if/else statement that keeps us out of the switch() if the user enters January(1) or February(2). If the user enters January, we add the day to the month value and skip everything else. If the user enters February, we bypass the section about Januray and then skip everything else. If the user enters a different month, we bypass the January & February sections and go right to the switch(). We have structured this this way because of the next section we're going to add which will determine if the year is leapyear. If the year is a leapyear, we need an extra day added to the months after February. If the date entered is February 29, the extra day is added already.
//get_date function(so far).
int get_date(int the_m, int the_day, int the_year){

//initial values for months of the year
  int jan = 0, febr = 31, mar = 59, apr = 90,
  may = 120, june = 151, july = 181, aug = 212,
  sept = 243, octo = 273, nov = 304, dec = 334;

  int the_month, the_date; //Variables used in calculations

if(3 > the_m){
    if(2 == the_m){
    the_date = febr + the_day;
    }
    else{
      if(1 == the_m){
      the_date = jan + the_day;
      }
    }
    }
    else{

   switch(the_m){
     case 3: the_month = mar; break;
     case 4: the_month = apr; break;
     case 5: the_month = may; break;
     case 6: the_month = june; break;
     case 7: the_month = july; break;
     case 8: the_month = aug; break;
     case 9: the_month = sept; break;
     case 10: the_month = octo; break;
     case 11: the_month = nov; break;
     case 12: the_month = dec; break;
   }
  if((0 == the_year%4) &! (0 == the_year%100)){
    the_date = the_day + (the_month + 1);
  }
    else{
      if(0 == the_year%400){
        the_date = the_day + (the_month + 1);
      }
      else{
        the_date = the_day + the_month;
      }
    }
 }

return 0;
}
Before we go any further, let's examine the if/else statements.

if
The if statement is a great way to do something in a program only when we want it to. Unchecked, program statements will execute every time the program runs, or every time a loop runs. if works much like it does in natural language. "if the light is on, turn it off." We don't want the light turned off if it already is. In real life doing such a thing would cause momentary confusion. In code, it will cause errors. This is called program flow control. Look at this example code:

int password;

cout << "Enter your password: ";
cin >> password;
if(password == 4819){
cout << "Access Granted!";
}

But what if they enter the wrong password? This is where we would use else.

else
In C++ else cannot be used without an if preceding it. However, if may be used by itself as we can see above. Let's add an else to our code snippet.

int password;

cout << "Enter your password: ";
cin >> password;
if(password == 4819){
cout << "Access Granted!";
}
else{
cout << "Access denied!";
}

if/else statements may be nested, meaning other if/else conditions may be placed within other if/else statements. This is where things can get very confusing very quickly. Be sure to use brackets -{ }- to open an close your statements and use proper indentation and line skipping to clearly indicate where one statement begins and the next one ends.

A nested if/else statement:

int num1 = 1;
int num2 = 2;
int num3;

if(num1 == 3){
  cout << "three";
}
else{
  if(num1 == 1){
    num3 = num1 + num2;
    cout << "three";
  }
  else{
    cout << "Not three";
  }
}
Looks dumb, but I couldn't think of anything else.
Back to our program.

At this point, if we returned the_date to the main program, we would get day number of the year (i.e., 308 for November 4th), but we want more that that. However, the number produced by the_date will be very useful to us. Our final output is going to be the day of the week and for that we need more calculations. For more calculations, we need another function. Before we start writing another function. First, let's take a step back and look at the whole program, what we have so far.
#include < stdio.h >
#include < iostream.h >

int get_date(int, int, int); //Our function declaration
int main()
{

int m, day, year; //month, day and year

  cout<< "\nEnter any date after 1900 as three sets of numbers.\n";
  cout<< "(month, day, year). Example: 7 29 1971 for July 29, 1971\n";
  cout<<"Entering invalid dates will exit the program.\n";
  cout<<"Enter date: ";
  cin>>m>>day>>year; //Take in our three variables

while((m != 13)&(day !=32)&(year != 0000)){
   //Invalid dates exit the loop

   get_date(m, day, year); //Our function call
}
  cout<<"\nYou entered an invalid date! End Program!" << endl;

return 0;
}


//get_date function(so far).
int get_date(int the_m, int the_day, int the_year){

//initial values for months of the year
  int jan = 0, febr = 31, mar = 59, apr = 90,
  may = 120, june = 151, july = 181, aug = 212,
  sept = 243, octo = 273, nov = 304, dec = 334;

  int the_month, the_date; //Variables used in calculations

if(3 > the_m){
    if(2 == the_m){
    the_date = febr + the_day;
    }
    else{
      if(1 == the_m){
      the_date = jan + the_day;
      }
    }
    }
    else{

   switch(the_m){
     case 3: the_month = mar; break;
     case 4: the_month = apr; break;
     case 5: the_month = may; break;
     case 6: the_month = june; break;
     case 7: the_month = july; break;
     case 8: the_month = aug; break;
     case 9: the_month = sept; break;
     case 10: the_month = octo; break;
     case 11: the_month = nov; break;
     case 12: the_month = dec; break;
   }
  if((0 == the_year%4) &! (0 == the_year%100)){
    the_date = the_day + (the_month + 1);
  }
    else{
      if(0 == the_year%400){
        the_date = the_day + (the_month + 1);
      }
      else{
        the_date = the_day + the_month;
      }
    }
 }

return 0;
}

Our new function will be called "get_year" and will be called from within our first function get_date. In order to figure out what day of the week a day fell on, we need to know first what the first day of a particular year was and then count up a week at a time. This is what our new function will do. Just like the first function, we will need to declare it at the top, call it from somewhere, and then create the function itself.


Continue Tutorial ----->