correctness - How to write correct code at the first time? -


I usually make many mistakes (logic errors, syntax errors) in the first attempt before completing some programming tasks. I have to write unit test to find those bugs. This is especially problematic when I am in an interview, in that situation, I am under pressure and I can not test my code with the compiler and the unit test.

My question is: How can I write the correct code in the first place? I know that it is difficult for the first time to have any practical approach to reducing bugs?

Thank you all.

I wanted to write a function that receives an integer array and an indicator for the size of the array. Fill that array with the principal number. This is not difficult at all, but I made many mistakes for the first time and continue searching for new bugs. Since it was a phone interview so I was asked to type the answer and send it the thought mail.

My first attempt

  Zero prime (int * array, int size) {bool isPrime = true; For (int i = 0; i  

Writing code in Gmail was a very bad idea. I would never do it again I knew that the program requires two for loop . However there are some major problems in the code

  1. At the end of the first loop 'I' should not be increased.
  2. If i search for a prime minister, then the array operation should be placed at the end of the loop
  3. Ol>

    My second try is, I have fixed some error and resubmitted it. .

      Zero prime (int * array, int size) {bool isPrime = true; For (int i = 0; i  

    There are still some basic errors in the code but my time has expired, I try to fix them in my third attempt.

      Zero prime (int * array, int size) assert (array! = Null) assert (size & gt; 0) Bool isPrime = true; For (int i = 0; i & lt; size;) {isPrime = true; For (int j = 2; j and lt; i / 2; j ++) {if (i% j == 0) {isPrime = false; } If (IsPrime) {* array = i; Array ++; I ++; Finally} After the interview, I thought that I really grew up I copied the code to my IDE, fixed all the bugs and tested it. I sent this to my interviewer and said sorry about it. I was really surprised that I could do some small problems.  Last Version     #include & lt; Iostream & gt; # Include & lt; Assert.h & gt; using namespace std; Zero prime (int * array, int size) {assert (array! = 0); Emphasis (size> 0); If (size == 1) {* array = 2; Return; } And {* array = 2; Array ++; } Bool isPrime = true; Int testNum = 3; For (int i = 1; i  

    Strong text

lot All the exercises :)

Although I do not think that some minor syntax errors are very much for an interviewer The more trouble will be - until your theory is sound.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -