just wondering if my program is optimized

Hi i'm currently doing a homework(I know that you will not give me the answer nor do i want it and i have finished it). basically my program makes a square with a given number , for example :
4
****
****
****
**** (4x4)

My teacher really care about optimization of the program and and i would like to know if you can give me some hint to where i could make some adjustment
thanks in advance.


#include <iostream>
using namespace std;
void affCote (int a){
     for( int i=0; i < a; i++){
     for( int i=0; i < a; i++){
       cout << "*";
          }
    cout << endl;
          }
}

int main()   {	
	int cote;
	char rep;
    do {
		cout << "Enter a number : "; 
    	cin >> cote;
    	if (cin.fail() || (cote<0)) {
    		cerr << "not a good number" << endl;
    		cin.clear();
    	}
    	else{
    		affCote(cote);
		}	
		cout << "continue? (o/n)";
		while (cin.get() != '\n') {} 
		cin >> rep;
		while (cin.get() != '\n') {} 
	} while (toupper(rep)== 'O');
    		
	return 0; 
}	
Last edited on
A note to all beginners wondering if their program is optimized, ask yourself this one question:

Are you having speed problems currently?

If the answer is no, then totally forget if your program is optimized or not. It's premature optimization, and that's a waste of time. The only times you should optimize your code is when you really need to.

Be careful, I'm not saying for you to practice terrible technique and don't care about your speed, but if your code is nice, readable, simple, and isn't causing any speed problems, then don't modify it at all.
_________________________________

To answer your question, yes, your code is optimal. If your teacher starts to complain about your beginner homework not being optimized enough for his standards, I have one word of advice for you:

Find a new teacher.

Seriously, if your teacher is going to try to push bad practices on his students then I personally don't think he or she should be teaching.
Last edited on
haha thanks for the answer but for my teacher the more optimize the better it is. anyways thanks for the information
Woah, I believe just found a bug in your program.

1
2
3
4
5
6
7
8
void affCote (int a){
     for( int i=0; i < a; i++){
     for( int i=0; i < a; i++){
       cout << "*";
          }
    cout << endl;
          }
}


Should be:

1
2
3
4
5
6
7
8
void affCote (int a){
     for( int i=0; i < a; i++){
     for( int j=0; j < a; j++){
       cout << "*";
          }
    cout << endl;
          }
}
Last edited on
Avilius wrote:
Woah, I believe just found a bug in your program.

While the second is more readable, the two snippets are equivalent.
Thanks cire, I was not aware.
thanks for the comments
Last edited on
Topic archived. No new replies allowed.