Here's the most simple and short approach (feel free to ask for more help):
First let's assign a number to each day of the week starting from Monday (or Sunday if you're that kind of person) to Sunday. We go from 0 to 6, so every day of the week has a unique number from 0 to 6, including both 0 and 6.
Now we ask the user how many days the month has, we carefully stow away this input into a variable.
Next, we ask him which day the month starts on. Using what we had assigned earlier, we use a for-loop to print spaces (i=0). The for-loop's condition is: until iterating variable is less than to the day entered.
So if I had typed in Monday, the for-loop would have no iterations and no spaces would be filled. Hence we get desired output of month starting from Monday.
If I typed something else for day, then the for-loop would print " " till for condition. So Tuesday would make it so that the for-loop prints one " ", and the " " occupies Monday's spot so we got what we wanted.
(You have to worry about tidying up the use of " "s)
Now we use a second for-loop which would loop until it's < or <= (depending on what value you gave the iterating variable) to the days of the month entered. Print iterating variable and " " (to tidy it a bit).
Remember: Make sure days cannot be greater than 31.
Now that's all done what about putting the days to the next line? See this is when our day's numeric value comes in handy.
So we need to print a "\n" after 5 in your example, but how do we know when to do it!
Inside the for-loop for printing days, we add an if condition:
1 2 3
|
if(inputted day's numeric value + i % 7 = 0) {
cout << "\n";
}
|
Brief explanation of above if condition: Try to relate this to your example, if Wednesday was the first day, we would have a numeric value of 2 for the day. 2 + 5 = 7, which is divisible by 7 to give a quotient of 0. Hence after the compiler prints 5, it comes to the if condition, checks it as true and prints a new line. Then days 6 onwards are printed on the next line. Similarly 2+12 = 14 which is divisible by 7 to give 0 quotient.
That's the logic behind this.
Now make sure that the if condition is the last thing in the for-loop, otherwise it would print "\n" too early!
Alright now you know what to do, go ahead and rock this! ;)