Sunday, May 5, 2013

Example for loop with Output

.
\\Prints a Fahrenheit-to-Celsius conversion table. This is easily accomplished with a for loop or a while loop:




#include<stdio.h>
#include<conio.h>
void main()
{
int a=0;
while(a<=100)
{
printf("%4d degree F=%4d degree C",a,(a-32)*5/9);
a=a+10;
}
getch();
}



If you run this program, it will produce a table of values starting at 0 degrees F and ending at 100 degrees F. The output will look like this:
 
 
   0 degrees F =  -17 degrees C
  10 degrees F =  -12 degrees C
  20 degrees F =   -6 degrees C
  30 degrees F =   -1 degrees C
  40 degrees F =    4 degrees C
  50 degrees F =   10 degrees C
  60 degrees F =   15 degrees C
  70 degrees F =   21 degrees C
  80 degrees F =   26 degrees C
  90 degrees F =   32 degrees C
 100 degrees F =   37 degrees C
 
 

C Errors to Avoid

  • Putting = when you mean == in an if or while statement
  • Forgetting to increment the counter inside the while loop - If you forget to increment the counter, you get an infinite loop (the loop never ends).
  • Accidentally putting a ; at the end of a for loop or if statement so that the statement has no effect - For example: for (x=1; x<10; x++); printf("%d\n",x); only prints out one value because the semicolon after the for statement acts as the one line the for loop executes.

No comments:

Post a Comment