Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not going to go into optimizing, because if you wanted better theoretical performance you would probably go with different data structures, such as ordered arrays/lists, trees, hash tables or some kind of indexing... None of that is relevant in this case, because you have a simple program dealing with a small amount of data.</p> <p>But I am going to tell you about the "excessive logic" your professor mentioned, taking your <code>searchInt</code> function as an example:</p> <pre><code>for (i=0;i&lt;num;i++) { if (s2[i].id == z) { printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept); break; } else if(i == num-1) { printf("nothing in id matches: &lt;%d&gt;\n\n",z); break; } } </code></pre> <p>The thing here is that every time around the loop you're testing to see if you're at the last element in the loop. But the loop already does that. So you're doing it twice, and to make it worse, you're doing a subtraction (which may or may not be optimized into a register by the compiler).</p> <p>What you would normally do is something like this:</p> <pre><code>int i; student *s = NULL; for( i = 0; i &lt; num; i++ ) { if( s2[i].id == z ) { s = &amp;s2[i]; break; } } if( s != NULL ) { printf( "struct variables are %d, %d, %s, %s\n\n", s-&gt;id, s-&gt;age, s-&gt;userName, s-&gt;dept ); } else { printf("nothing in id matches: &lt;%d&gt;\n\n",z); } </code></pre> <p>See that you only need to have some way of knowing that the loop found something. You wait for the loop to finish before you test whether it found something.</p> <p>In this case I used a pointer to indicate success, because I could then use the pointer to access the relevant record without having to index back into the array and clutter the code. You won't always use pointers.</p> <p>Sometimes you set a flag, sometimes you store the array index, sometimes you just return from the function (and if the loop falls through you know it didn't find anything).</p> <p>Programming is about making sensible choices for the problem you are solving. Only optimize when you need to, don't over-complicate a problem, and always try to write code that is easy to read/understand.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload