Wednesday, July 28, 2010

Over and Over Again

We started our tutorial with the while loop. It allows one to perform an action over and over again until a condition becomes true. Another construct that is similar in result but different in syntax is the for loop.
A lot of times when a loop is used, we are interested in having a initialization, a conditional check and an action that changes the value of that variable. The syntax of the for loop contains precisely these three parts.
for (; ; )
Suppose you were helping a younger friend to learn tables and you wanted to print out the table of any number given to your program as input. Here is how the program would look.
#include”stdio.h”
int main()
{
int i, num;
printf(“Enter a number to see its tables\n”);
scanf(“%d”, &num);
for (i=1; i<11; i++)
{
printf(“%d\n”, i*num);
}
}
Done. As simple as that. The initialization of the variable, the condition check and its increment is all done in one statement. The first time the execution reaches the printf function, the i=1 has been executed and the condition check i<11 has been performed. The increment has not yet been visited. After the printf is executed, the execution pointer returns to the for construct, increments the variable and then checks for the condition. Though most of the times one will use the for loop in a very mechanical manner without giving much thought to the sequence of things happening, one must never forget the path taken by the execution pointer. I will show a cool program that will demonstrate the validity of my previous statement and establish it without doubt.
#include “stdio.h”
int main()
{
int i=0;
for (printf("Initialization\n"); printf("Condition check\n"); printf("Action on variable\n"))
{
printf("Inside loop\n");
i++;
if (i>2)
{break;}
}
}
Output:
Initialization
Condition check
Inside loop
Action on variable
Condition check
Inside loop
Action on variable
Condition check
Inside loop

Hope this program has helped you understand the sequence of steps undertaken by the execution of the for loop. One must understand that the loop body is visited at least once because the condition is evaluated to true. This indicates that the printf function must return something. Yes, it does. It returns the number of characters output to the screen. Instead of “Condition check\n”, if I had written a blank string “” then printf would have returned 0 and the condition check would have failed. The body would have not been visited even once.
We have introduced a new keyword break. Execution of break causes the execution pointer to abruptly pre-empt the loop and come out of it irrespective of what the condition check says. break works with for, while and switch…case but not with if. Also, it only breaks the encompasing loop not any loop beyond that. The execution pointer will be at the closing } of the for loop as a result of the break statement being executed.
Okay, now that you have started feeling that for loops are simple, let us complicate things a bit more. Suppose you want the following output:

    *
   ***
  *****
 *******
*********

How can this be accomplished? By using double for loops. Here is the program:
#include”stdio.h”
int main()
{
 int i,j;
 for (i=0;i<5;i++)
 {
  for (j=5;j>i;j--)
  {
   printf(" ");
  }
  for (j=0;j<2*i+1;j++)
  {
   printf("*");
  }
  printf("\n");
 }
 scanf("%d",&i);
}
Yes, it is a bit complicated, but try to understand the working yourself. Look at the stars carefully and observe the repetition structure. First of all, there are repeated spaces. Then there are repeated stars. Finally this all is repeated in every row, but the number of spaces decreases and number of stars increases. If you find this program a bit too complex, let me give a simpler assignment:
*
***
*****
*******
*********
This program is relatively simpler. It only has two repetitions.
for (i=0;i < 5;i++)
{
 for (j=0;j<2*i+1;j++)
 {
  printf("*");
 }
 printf("\n");
}
This is how you can have a for loop inside another. It has allowed us to grow the number of stars on each consecutive line (next line is reached because of the printf(“\n”) statement). A loop inside another gives a 2d representation. If we increase it to one more loop inside, we will have a 3d structure. Of course it is very difficult to show such a structure on the screen. Beyond that I have not seen many programs.

Conditional Checks

The contractor whom you worked for is impressed by your work. Your pavement cost calculator system is very useful for his customers. One day, the contractor calls you to his office and asks if you could create an inventory system for him. You are not sure and come to me for advice. Yes, you can create an inventory system for the contractor. But before that you have a long way to go. I promise to teach you C/C++ but it is up to you to apply it.
We will look at the C/C++ constructs that you will need going ahead step by step. For starters let’s say that the contractor has two type of paving blocks; one with rounded edges and another with square edges. The rate depends on which type of blocks the customer chooses.
We need a modification in the cost calculation program which will give the customer a choice of the type of paving blocks. This brings us to the if statement. The if…else block is a condition checker. Statements after the if are performed only if the condition is true, otherwise those after else are performed. The else part is not compulsory. Its syntax is as follows:
if (condition)
{
//true part
}
else
{
//false part
}
Just as we mentioned for the while loop, a condition can be anything that can be evaluated to either a zero or a non-zero value. Also notice the scope defining {…}.
To show how the if construct is used, let us write the cost calculation program again.
#include”stdio.h”
int main()
{
int len1, width1, len2, width2, rate, area, typeOfPayment;
printf(“Enter the outside length\n”);
scanf(…);
…
printf(“Select one of the following pavement types\n”);
printf(“1. Rounded Pavements\n”);
printf(“2. Square Pavements\n”);
scanf(“%d”, &typeOfPayment);
…
if (1 == typeOfPayment)
{
rate = 150;
}
else
{
rate = 120;
}
…
}
Now what if there are three kinds of pavement blocks?

if (1 == typeOfPayment)
{ rate = 150; }
else if (2 == typeOfPayment)
{ rate = 120; }
else
{ rate=180; }
The keen observer would have noticed two unusual things. I always leave a white space between if and the “(” but there is no space between printf and “(”. That is just a good programming practice. It is a subtle way to differentiate functions from keywords. Keywords such as if, for, while, switch which have a parenthesis will always have a space between the word and the parenthesis. On the other hand, functions such as main, printf will have no whitespace between the end of the word and the beginning of the parenthesis.
The other thing which is less subtle is the condition inside the if parenthesis. I have always written the constant literal (1, 2 or 3) first and then equated it to the variable. It is not necessary to write in this form and if (typeOfPayment == 2) is equally correct. However, it is important that one not forget to use the double= sign. Instead if someone uses a single equal, typeOfPayment will be assigned the value of 2 rather than being checked if it is equal to one. Moreover, since this assignment will succeed, the result of the condition will be always evaluated to true! If however, one writes the literal as the first operand, and then inadvertently uses the single= the compiler will complain since assignments to literals is not possible. Your mistake of using single= will not go unnoticed. I understand that some people find it easier to remember that they must use == and not = instead of this roundabout manner of comparing variables to literals. Nonetheless many developers follow the style I will follow here. Java does not allow only = inside the if statement(condition must strictly evaluate to Boolean), hence this quirkiness does not apply to Java.