Iteration
Source Code from Notes
Example 1
This example reverses the digits of a number, and prints out the number in
the reverse order. Each digit is displayed as it is extracted by the
program. The final call to \fC\s8printf\fR\s0 returns the cursor to the
next line as the newline character has not been included within the
loop.
#include <stdio.h>
main()
{
int number, right_digit;
printf("Enter your number\n");
scanf("%d",&number);
while (number !=0)
{
right_digit = number % 10;
printf("%d",right_digit);
number /= 10;
}
/*return cursor to next line*/
printf("\n");
}
Example 2
This example checks that the input value is in the desired range
#include <stdio.h>
#define max 100
#define min 1
main()
{
int number;
number = 0;
while ( number < min || number > max)
{
printf("Enter a number in the range 1 to 100\n");
scanf("%d",&number);
}
printf("the number is in range\n");
}
Example 3
#include <stdio.h>
main()
{
char letter;
printf("Press Y to continue\n");
do
{
letter = getchar();
} while (letter != 'y' && letter != 'Y');
printf("program execution will continue\n");
}
Example 4
The following program creates a conversion table for converting inches to
centimetre. The values in the table are calculated for inches in the range
1 to 10 in half inch increments.
#include <stdio.h>
main()
{
float inches,centimetres;
/* print table header*/
printf("inches\et centimetres\n");
/*calculate and print table entries*/
for (inches = 1; inches <=10 ; inches += 0.5)
{
centimetres = 2.54 * inches;
printf("%6.2f %7.2f\n",inches,centimetres);
}
}