C/Language Basics/Do While
Содержание
A flag: informs a certain condition has occured
#include <stdio.h>
int main() {
int temp;
float celsius;
char repeat;
do {
printf("Input a temperature:");
scanf("%d", &temp);
celsius = (5.0 / 9.0) * ( temp - 32 );
printf("%d degrees F = %6.2f degrees celsius\n", temp, celsius);
printf("Continue (y or Y)?");
repeat = getchar();
putchar("\n");
} while(repeat == "Y" || repeat=="y");
}
Do while loop
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Enter some text (type a period to quit).\n");
do {
ch = getchar();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != ".");
return 0;
}
Do while loop for your selection
#include <stdio.h>
int main(void) {
char ch;
do {
printf("Load, Save, Edit, Quit?\n");
do {
printf("Enter your selection: ");
ch = getchar();
} while(ch!="L" && ch!="S" && ch!="E" && ch!="Q");
if(ch == "Q") {
printf("Exit.");
}
} while(ch != "Q");
return 0;
}
Do while loop with continue
#include <stdio.h>
int main(void) {
int total, i, j;
total = 0;
do {
printf("Enter a number (0 to stop): ");
scanf("%d", &i);
printf("Enter the number again: ");
scanf("%d", &j);
if(i != j) {
printf("Mismatch\n");
continue;
}
total = total + i;
} while(i);
printf("Total is %d\n", total);
return 0;
}
Do while with char value as condition
#include <stdio.h>
main()
{
char ch;
ch = "a";
do
printf ( "%c", ch );
while ( ch++ < "z" );
printf ( "\n" );
}
Nested for loop inside a do while loop
#include <stdio.h>
#include <conio.h>
int main(void)
{
int i, j, k, m;
do {
printf("Enter a value: ");
scanf("%d", &i);
m = 0;
for(j=0; j<i; j++)
for(k=0; k<100; k++)
m = k + m;
} while(i>0);
return 0;
}
Reversing the digits: do while
#include <stdio.h>
void main() {
int number = 123; /* The number to be reversed */
int reversedNumber = 0; /* The reversed number */
int temp = 0; /* Working storage */
temp = number; /* Copy to working storage */
/* Reverse the number stored in temp */
do
{
reversedNumber = 10 * reversedNumber + temp % 10; /* Add the rightmost digit */
temp = temp/10; /* Remove the rightmost digit */
} while (temp); /* Continue while temp>0 */
printf ("\nThe number %d reversed is %d rebmun ehT\n",
number, reversedNumber );
}