• 0

My first VC++ Program.


Question

#include <iostream>

int month(int m,int y)
	{
	int x=1, c=0; 

	  while(x<m)
	  {

		if((x==2)&&((y%4)==0))
			c=c+29;
			else if((x==1||x==3||x==5||x==7||x==8||x==10||x==12))
				c=c+31;
			else if((x==4||x==6||x==9||x==11))
				c=c+30;
			else if((x==2)&&((y%4)!=0))
				c=c+28;
			x=x+1;
		}

		return c;
		}

int daycalc(int d,int m,int y)
	{
	int dd, ind, x;
	x=(y-1)/4;
	dd=month(m, y)+d+(y-x-2)*365+(x+1)*366;
	ind=dd%7;
	return(ind);

		}

int validate(int d,int m,int y)
	{

	if((m<1)||(m>12)||(y<0)||(d<1))
		return(0);
	else if((m==2)&&((y%4)==0)&&(d<=29))
		return(1);
	else if((m==1||m==3||m==5||m==7||m==8||m==10||m==12)&&(d<=31))
		return(1);
	else if((m==4||m==6||m==9||m==11)&&(d<=30))
		return(1);
	else if((m==2)&&((y%4)!=0)&&(d<=28))
		return(1);
		return(0);
		}
int checkdate(int d,int m,int y)
	{
		int x=0;
		x=daycalc(d, m, y);

	if(validate(d, m, y)==0)
		return (7);
	else if(validate(d, m, y)==1)
		return x;

		return (7);
		}
void getdayname(int d,int m,int y)
	{
	if (checkdate(d, m, y)==7)
		std::cout<<"Invalid Date Entered";
	else if(checkdate(d, m, y)==1)
		std::cout<<"Saturday. ";
	else if(checkdate(d, m, y)==2)
		std::cout<<"Sunday. ";
	else if(checkdate(d, m, y)==3)
		std::cout<<"Monday. ";
	else if(checkdate(d, m, y)==4)
		std::cout<<"Tuesday. ";
	else if(checkdate(d, m, y)==5)
		std::cout<<"Wednesday. ";
	else if(checkdate(d, m, y)==6)
		std::cout<<"Thursday. ";
	else if(checkdate(d, m, y)==0)
		std::cout<<"Friday. ";
		}

void main()
{
	int ddd=0,mmm=0,yyyy=0;
	int a=1;
	std::cout<<std::endl<<"Enter the date to findout the day.";
	while(a!=0)
	{
	std::cout<<std::endl<<std::endl<<"Enter Date: ";
	std::cin>>ddd;
	std::cout<<"Enter Month: ";
	std::cin>>mmm;
	std::cout<<"Enter Year: ";
	std::cin>>yyyy;
	getdayname(ddd,mmm,yyyy);
	std::cout<<std::endl<<"Enter 0 to exit, or any number to continue."<<std::endl;
	std::cin>>a;
	}
}

Well this is my first program in VC++ (Express).(Have done elementary programming in Borland)

As u must have known by known by now, it is a program to find out the name of the day.

The problem i am facing is, that the daycalc function is being executed 5 times, instead of one.

apart from that, what i want to know is that, is my programming style good and efficient(To debug)??

if not where should i be improving??

.

Also, Is VC++ a good platform for beginners?

Thanks.

Edited by Ksquare
Link to comment
Share on other sites

22 answers to this question

Recommended Posts

  • 0

Checkdate calls daycalc, for each case it doesn't match, the next 'else if' structure will execute. Since you keep testing it, it keeps calling daycalc. That's why it's happening multiple times.

As for VC++, I think it's a little too feature rich for a beginner, but if you're comfortable in it stick with it. I would typically recommend someone to start with something like Code::Blocks and move up, but if you have no problem with it and are familiar with most of the features that's great.

As for the code, it's expected to look like spaghetti code from a beginner :p . As you progress you will find shortcuts like the switch statement and arrays/vectors that will make your life easier. It can probably be completed in 1/4 the code but it's a great effort.

Link to comment
Share on other sites

  • 0
Checkdate calls daycalc, for each case it doesn't match, the next 'else if' structure will execute. Since you keep testing it, it keeps calling daycalc. That's why it's happening multiple times.

As for VC++, I think it's a little too feature rich for a beginner, but if you're comfortable in it stick with it. I would typically recommend someone to start with something like Code::Blocks and move up, but if you have no problem with it and are familiar with most of the features that's great.

As for the code, it's expected to look like spaghetti code from a beginner :p . As you progress you will find shortcuts like the switch statement and arrays/vectors that will make your life easier. It can probably be completed in 1/4 the code but it's a great effort.

Thanks a ton. :D I tried to make it very modular, so that it would be easy to debug.

(I am not so good at debugging. Just seeing many lines of coding jammed up in a single function gives me nightmares. )

As for the switch statement, i know about it, but sort of hate it.( coz i think , it's not versatile enough.)

I am currently having Ivor Horton(Wrox) , Is it good??

Edited by Ksquare
Link to comment
Share on other sites

  • 0
Thanks a ton. :D I tried to make it very modular, so that it would be easy to debug.

(I am not so good at debugging. Just seeing many lines of coding jammed up in a single function gives me nightmares. )

As for the switch statement, i know about it, but sort of hate it.( coz i think , it's not versatile enough.)

I am currently having Ivor Horton(Wrox) , Is it good??

Learn to like the switch statement. It can make your code look simpler and a lot neater. Yes technically its not as versatile as an IF, but you could also have IF's within each case of the switch.

Take your getdayname function as an example:

void getdayname(int d,int m,int y)
		 {
		 if (checkdate(d, m, y)==7)
			 std::cout<<"Invalid Date Entered";
		 else if(checkdate(d, m, y)==1)
			 std::cout<<"Saturday. ";
		 else if(checkdate(d, m, y)==2)
			 std::cout<<"Sunday. ";
		 else if(checkdate(d, m, y)==3)
			 std::cout<<"Monday. ";
		 else if(checkdate(d, m, y)==4)
			 std::cout<<"Tuesday. ";
		 else if(checkdate(d, m, y)==5)
			 std::cout<<"Wednesday. ";
		 else if(checkdate(d, m, y)==6)
			 std::cout<<"Thursday. ";
		 else if(checkdate(d, m, y)==0)
			 std::cout<<"Friday. ";
			 }

becomes

void getdayname(int d,int m,int y){	
		 switch(checkdate(d, m, y)){
			 case 0: std::cout<<"Friday. ";	  break;
			 case 1: std::cout<<"Saturday. ";	break;
			 case 2: std::cout<<"Sunday. ";	  break;
			 case 3: std::cout<<"Monday. ";	  break;
			 case 4: std::cout<<"Tuesday. ";	 break;
			 case 5: std::cout<<"Wednesday. ";   break;
			 case 6: std::cout<<"Thursday. ";	break;
			 default: std::cout<<"Invalid day!"; break;
		 }
	 }

Switch makes it easier to understand than trying to follow than 6 else IF's doesn't it? :p

Also instead of writing std::cout each time, at the top of your program if you write using namespace std, this allows you to drop the std:: and just write cout instead. Same goes for cin too :)

If you want to, you could also get rid of some of the 'magic numbers' and replace them with more meaningful names using the #define preprocessor definition.

For example:

#define JANUARY 1
#define FEBRUARY 2

if(m == JANUARY || m == FEBRUARY){
	// code
}

etc!

Also, Is VC++ a good platform for beginners?

Thanks.

Erm it's actually maybe a little complex for your first dive into programming although it is a great IDE. Maybe look at Dev C++ or Code::Blocks

Edited by ViZioN
Link to comment
Share on other sites

  • 0
I consider Java a good first language.

Thanks, but i'll first try VC++.

Switch makes it easier to understand than trying to follow than 6 else IF's doesn't it?

Also instead of writing std::cout each time, at the top of your program if you write using namespace std, this allows you to drop the std:: and just write cout instead. Same goes for cin too

.

Thanks, for the namespace std. it s**ks to write std:: everytime.

Will surely use switch frm now on.(Feeling foolish already. :blush: )

If you want to, you could also get rid of some of the 'magic numbers' and replace them with more meaningful names using the #define preprocessor definition.

Thanks for that too.( :cool: )

Edited by Ksquare
Link to comment
Share on other sites

  • 0
Thanks, for the namespace std. it s**ks to write std:: everytime.

Will surely use switch frm now on.(Feeling foolish already. :blush: )

Haha yes it will save you a lot of typing! Sometimes you will need to use IF's rather than switch, especially if you're not using integers, but a lot of the time a switch statment can make things a lot more readable :) Good first program though! Don't feel foolish...you have to start somewhere. As you make more programs you'll start to notice little tricks too that save time / lines of code.

You've also tried to perform some input validation which is a great thing to try and do. It's actually quite difficult to make it bulletproof but for checking dates etc you've been pretty thorough.

Link to comment
Share on other sites

  • 0
You've also tried to perform some input validation which is a great thing to try and do. It's actually quite difficult to make it bulletproof but for checking dates etc you've been pretty thorough.

Geez, :blush: Thanks Sir.

That's the very reason i tried to make it very modular, coz when it comes at finding errors(Logical) i am very impatient, and get easily frustated.

I don't mind taking hours on end to finish it, but when i run it , it shud work properly. Hunting for errors makes me mad (I am really poor at it.)

It's actually my first VC++ program, I was using the Borland Compiler [TurboC]. Should i continue with it??

I used VC++, because i really liked the Intellisense feature.

Earlier on, i had learned C++ upto Arrays and Pointers(not fully) using the TurboC IDE. It's been a long time since then (almost a year) coz i couldn't continue with C++.

This time i am hoping to finish it though.

One more request, is writing programs in a modular way really good or shud i try to make the coding more consolidated?

coz it really takes up a lot of lines.

Is Ivor Horton (Wrox) a good book?

Thanks a ton, sir.

Edited by Ksquare
Link to comment
Share on other sites

  • 0

Modular is good. Don't worry about trying to fit all your code into one big main() function. You're going about it the right way by breaking it down into smaller chunks. In larger programs this is taken a step further, by splitting code into separate source files, each with their own header. For example one source file may handle validation, another handles storage of data into external files, etc.

Breaking down your code also allows you to re-use the function, and in the future use it within other programs etc. Spotting errors is a skill you improve with experience, normally by making the errors :p Compilers are pretty good now-a-days at telling you where the error is, you just have to try and interpret it correctly.

I haven't used Borland Turbo C so I can't give an opinion of it, and even though I haven't actually used VC++ much I still quite like it, although I'm more used Dev C++ or a plain text editor and I compile it myself :p

Arrays and pointers is a good next step. Pointers take a bit of getting your head around, but being able to work with them is vital.

I haven't read any books by Ivor Horton, but if you're looking for a great set of tutorials for C++ look here. It covers pointers, arrays, classes and general input/output to files.

Link to comment
Share on other sites

  • 0
I consider Java a good first language.

My least favourite language! I would have said C# or vb.net as a starter, definately a more gentle introduction than C++

As has already been pointed out case block would be more efficient than the if else's but a day array would be better still, the it's a single line of code.

One tip when searching for solutions to problems is to search Google groups not just the web.

Edited by m.keeley
Link to comment
Share on other sites

  • 0
Modular is good. Don't worry about trying to fit all your code into one big main() function. You're going about it the right way by breaking it down into smaller chunks. In larger programs this is taken a step further, by splitting code into separate source files, each with their own header. For example one source file may handle validation, another handles storage of data into external files, etc.

Breaking down your code also allows you to re-use the function, and in the future use it within other programs etc. Spotting errors is a skill you improve with experience, normally by making the errors :p Compilers are pretty good now-a-days at telling you where the error is, you just have to try and interpret it correctly.

I haven't used Borland Turbo C so I can't give an opinion of it, and even though I haven't actually used VC++ much I still quite like it, although I'm more used Dev C++ or a plain text editor and I compile it myself :p

Arrays and pointers is a good next step. Pointers take a bit of getting your head around, but being able to work with them is vital.

I haven't read any books by Ivor Horton, but if you're looking for a great set of tutorials for C++ look here. It covers pointers, arrays, classes and general input/output to files.

Thanks Sir.

I am really a pro at making errors.

(if you find less than 10 errors, it ain't me , esp becoz i dont start with making flowcharts. :s )

Compiling with Borland was a pain. It's much easier with VC++.

The last time i tried Pointers, i found it pretty tough. :dontgetit:

(esp. coz the tutor at school was such an idiot. Sometimes i used to feel like digging the compass up his butt. But i couldn't :argh: ).

The site was good, thanks for the links, sir.

Edited by Ksquare
Link to comment
Share on other sites

  • 0

VC++ rocks, period.

As for if your programming is efficient or modular etc, that would be difficult to answer based on your test case. You see, you don't make something modular for the sake of good programming style, you make something modular if and when you expect this area of your program to change. The overhead in making the code modular now is a good investement if it can potentially save you lots of headaches and tedious rewrites later in the project. For instance, in a real-world scenario, with a medium-sized application, you'd probably want to create a DateTime type to encapsulate all data related to representing a date instead of flinging around integers. But is it worth the trouble in your case? I don't know, because all your main() tells me is that you're going to do a few inputs and outputs and be done with it.

Something you can apply to any project, though, is to try to make your code as simple and intuitive as possible. Put yourself in the shoes of another programmer trying to understand what your code does, and make him have almost nothing to "figure out". It should all be very plain and obvious.

For instance, when I read your method month, first, I wonder what it does. Just reading the declaration, I see it's called month, it takes two ints named m and y, and returns an int. I take a wild guess and suppose "y" stands for a year and "m" for a month, but I've no idea what it returns. A month? Based on a year and a month?

Next line. It will use an integer named x and another named c. I am just more and more clueless. Then I see a while loop with a lot of conditions that don't make any sense to me, and finally c is returned.

That is bad style. Your method does something: the name should say what it does. Your variables represent something; their name should be what they represent. If you have complex conditionals, you could either write a comment to indicate what you are checking for, or store the conditional expression result in a boolean and use that boolean in the if statement: the name of the boolean says what the condition is.

Quiz: what's the purpose of the following method?

int xyz(){
	return random() % 2 ? 0 : 1;
}

Now, what's the purpose of the following method?

Side TossCoin() {
	if (random() % 2 == 0)
		 return Side.Head;
	else
		 return Side.Tail;
}

You probably can figure out that xyz() returns a random value in the integer range 0:1, but you probably can't figure out that it really simulates flipping a coin. For the computer, it amounts to the same thing, but not for the reader.

Edited by Dr_Asik
Link to comment
Share on other sites

  • 0
My least favourite language! I would have said C# or vb.net as a starter, definately a more gentle introduction than C++

As has already been pointed out case block would be more efficient than the if else's but a day array would be better still, the it's a single line of code.

One tip when searching for solutions to problems is to search Google groups not just the web.

I second that.

But in many schools here, they teach Java (Using the BlueJ IDE) before C or C++.

Some even teach LOGO. :laugh:

Link to comment
Share on other sites

  • 0
VC++ rocks, period.

Quiz: what's the purpose of the following method?

int xyz(){
	return random() % 2 ? 0 : 1;
}

Now, what's the purpose of the following method?

Side TossCoin() {
	if (random() % 2 == 0)
		 return Side.Head;
	else
		 return Side.Tail;
}

You probably can figure out that xyz() returns a random value in the integer range 0:1, but you probably can't figure out that it really simulates flipping a coin. For the computer, it amounts to the same thing, but not for the reader.

Thanks sir.

I get what you are saying.

Making the purpose of the code easily understandable is really Important.

From the next time onwards, i will try to be more cautious, though.

Link to comment
Share on other sites

  • 0
#include <iostream>

int month(int m,int y)
	{
	int x=1, c=0; 

	  while(x<m)
	  {

		if((x==2)&&((y%4)==0))
			c=c+29;
			else if((x==1||x==3||x==5||x==7||x==8||x==10||x==12))
				c=c+31;
			else if((x==4||x==6||x==9||x==11))
				c=c+30;
			else if((x==2)&&((y%4)!=0))
				c=c+28;
			x=x+1;
		}

		return c;
		}

Sometimes it's worthwhile to pre-calculate certain things instead of doing it all on the fly. It makes your code easier to read as well.

This function could be rewritten like this:

int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int monthsleap[12] = {31,29,31,30,31,30,31,31,30,31,30,31};

int month(int m,int y)
{
	int c=0;

	int *mt;
	if(y%4==0)
		mt=monthsleap;
	else
		mt=months;

	for(int x=0;x<m-1;x++)
		c+=mt[x];

	return c;
}

Instead of doing all these comparisons, we're now just placing the amount of days in each month in lookup tables (in this case an array of integer values) and then setting the "mt" pointer to the correct table to account for leap years. We then use this table in our loop, turning it into a simple addition with no comparisons. We've also placed the modula to check for leap years outside of the loop, so the calculation is only performed once, rather than once for each iteration of the loop. This is usually a good idea, as the less work we do in our loop the faster it will run.

int validate(int d,int m,int y)
	{

	if((m<1)||(m>12)||(y<0)||(d<1))
		return(0);
	else if((m==2)&&((y%4)==0)&&(d<=29))
		return(1);
	else if((m==1||m==3||m==5||m==7||m==8||m==10||m==12)&&(d<=31))
		return(1);
	else if((m==4||m==6||m==9||m==11)&&(d<=30))
		return(1);
	else if((m==2)&&((y%4)!=0)&&(d<=28))
		return(1);
		return(0);
		}

int checkdate(int d,int m,int y)
	{
		int x=0;
		x=daycalc(d, m, y);

	if(validate(d, m, y)==0)
		return (7);
	else if(validate(d, m, y)==1)
		return x;

		return (7);
		}

The same applies here. Reusing the month tables gives us:

bool validate(int d,int m,int y)
{

	if((m<1)||(m>12)||(y<0)||(d<1))
		return false;

	if(y%4==0)
	{
		if(d<=monthsleap[m-1])
			return true;
	}
	else
	{
		if(d<=months[m-1])
			return true;		
	}

	return false;
}

int checkdate(int d,int m,int y)
{
	if(validate(d, m, y))
		return daycalc(d, m, y);

	return (-1);
}

void getdayname(int d,int m,int y)
	{
	if (checkdate(d, m, y)==7)
		std::cout<<"Invalid Date Entered";
	else if(checkdate(d, m, y)==1)
		std::cout<<"Saturday. ";
	else if(checkdate(d, m, y)==2)
		std::cout<<"Sunday. ";
	else if(checkdate(d, m, y)==3)
		std::cout<<"Monday. ";
	else if(checkdate(d, m, y)==4)
		std::cout<<"Tuesday. ";
	else if(checkdate(d, m, y)==5)
		std::cout<<"Wednesday. ";
	else if(checkdate(d, m, y)==6)
		std::cout<<"Thursday. ";
	else if(checkdate(d, m, y)==0)
		std::cout<<"Friday. ";
		}

If we keep applying the same logic, we can also simplify this function using a lookup table:

char *days[] = {"Friday","Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
void getdayname(int d,int m,int y)
{
	int day = checkdate(d,m,y);

	if(day==-1)
		std::cout << "Invalid date";
	else
		std::cout << days[day];
}

Link to comment
Share on other sites

  • 0
Sometimes it's worthwhile to pre-calculate certain things instead of doing it all on the fly. It makes your code easier to read as well.

This function could be rewritten like this:

int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int monthsleap[12] = {31,29,31,30,31,30,31,31,30,31,30,31};

int month(int m,int y)
{
	int c=0;

	int *mt;
	if(y%4==0)
		mt=monthsleap;
	else
		mt=months;

	for(int x=0;x<m-1;x++)
		c+=mt[x];

	return c;
}

Instead of doing all these comparisons, we're now just placing the amount of days in each month in lookup tables (in this case an array of integer values) and then setting the "mt" pointer to the correct table to account for leap years. We then use this table in our loop, turning it into a simple addition with no comparisons. We've also placed the modula to check for leap years outside of the loop, so the calculation is only performed once, rather than once for each iteration of the loop. This is usually a good idea, as the less work we do in our loop the faster it will run.

The same applies here. Reusing the month tables gives us:

bool validate(int d,int m,int y)
{

	if((m<1)||(m>12)||(y<0)||(d<1))
		return false;

	if(y%4==0)
	{
		if(d<=monthsleap[m-1])
			return true;
	}
	else
	{
		if(d<=months[m-1])
			return true;		
	}

	return false;
}

int checkdate(int d,int m,int y)
{
	if(validate(d, m, y))
		return daycalc(d, m, y);

	return (-1);
}

If we keep applying the same logic, we can also simplify this function using a lookup table:

char *days[] = {"Friday","Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
void getdayname(int d,int m,int y)
{
	int day = checkdate(d,m,y);

	if(day==-1)
		std::cout << "Invalid date";
	else
		std::cout << days[day];
}

Thanks a lot, sir.

I am really obliged. :cool:

Makes me feel silly for not doing the Pre-Calculation thing.(Inspite of reading many times, that it shud be done.)

I am really surprised at how short the entire code has become! Its easier to read too.

Guess i need a lot more serious practice now (And in the right way).

Thanks again to all of you for being so supportive. :)

Link to comment
Share on other sites

  • 0
Thanks a lot, sir.

I am really obliged. :cool:

Makes me feel silly for not doing the Pre-Calculation thing.(Inspite of reading many times, that it shud be done.)

I am really surprised at how short the entire code has become! Its easier to read too.

Guess i need a lot more serious practice now (And in the right way).

Thanks again to all of you for being so supportive. :)

There's no need to feel silly :)

When we're starting out learning our first programming language, we all have to start from scratch, as you have done. My first language was C++ and I first learnt to do it the way you did in your original post. It's not till a few months afterwards that I learnt about arrays and how they can be used to make code much more efficient. Just like you have now :)

It's all a learning curve. Good luck with your programming studies :)

Link to comment
Share on other sites

  • 0
Also, Is VC++ a good platform for beginners?

Thanks.

No it is not.

It is a declining language currently, still the third most popular, but it is going down.

It main problem is it requires so much coding to do so little. Of course is very difficult to learn especially if you do GUI programming.

Pretty much anything else is better in that respect.

Usually the language I recommend for beginners or experts are in order

1) python

2) Delphi .NET

3) C#

4) Java

with python being the clear winner. Of course you have nothing to lose in learning C++.

Link to comment
Share on other sites

  • 0

My first serious venture in programming was in C++. It was indeed very painful, but the good thing about that is that once you've been through C++, anything else seems easy and elegant. Also, doing C++ makes you able to better understand higher-level languages like C# and Python, just like doing Assembly gives you a much better understanding of C.

As for its decline, although I would myself very much like it to happen (die C++!!! :angry: ), C++ has apparently been in decline for above a decade now, and somehow it's still the standard in the gaming industry and plays a central role in several other domains. There is definitely room for growth for Python and newer languages, but C++ isn't going anywhere anytime soon.

For a highly motivated beginner, C++ is a logical choice I believe.

Link to comment
Share on other sites

  • 0
No it is not.

It is a declining language currently, still the third most popular, but it is going down.

It main problem is it requires so much coding to do so little. Of course is very difficult to learn especially if you do GUI programming.

Pretty much anything else is better in that respect.

Usually the language I recommend for beginners or experts are in order

1) python

2) Delphi .NET

3) C#

4) Java

with python being the clear winner. Of course you have nothing to lose in learning C++.

You think C++ is dying let you recommend Delphi .NET, ahaha... oh wow.

Link to comment
Share on other sites

  • 0
You think C++ is dying let you recommend Delphi .NET, ahaha... oh wow.

I think you are confused.

I said that C++ is declining not dying. There is a great difference between the two.

DELPHI is dying.

However on the other hand DELPHI .NET is a fully compliant .NET language capable of 100% access to .NET framework and any third party libraries with no additional code. As .NET frame is thriving in windows platform . (and exist in other other platforms supported by MONO project). Thus DELPHI NET is thriving as well . (as does other .net languages like C#, C++ .NET and VB .NET)

this a website that address language popularity.

http://www.tiobe.com/index.php/content/pap...tpci/index.html

Edited by kilon
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.