APS105 L08 - While Loops

#APS105 Slides Lecture Link to web notes

Syntax:

while (<statement>) {
	<expression>
}

Example:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
int count = 10;
while (count > 0) {
printf("Countdown: %02d\n", count); // always prints with leading 0
--count; // subtract 1 from count each time
}
printf("Blast off!\n");
return EXIT_SUCCESS;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
	int input = 0;
	printf("Input a positive integer: ");
	scanf("%d", &input);
	int num_digits = 0;
	while (input > 0) {
		input /= 10; // divides input by 10 repeatedly until it is less than 0.
		++num_digits;
	}
	printf("Number of digits: %d\n", num_digits);
	return EXIT_SUCCESS;
}

Do while loops

A form of while loop that runs at least once, and then may repeat based on the statement in the do {} part.

Syntax:

do {
	<statement>
} while (<expression>);

E.g., repeat asking for positive integer until user inputs a positive integer

#include <stdio.h>
#include <stdlib.h>
int main(void) {
	int input = 0;
	do {
		printf("Input a positive integer: ");
		scanf("%d", &input);
	} while (input <= 0);
	// if user inputs negative input, repeat do {} expression.
	
	printf("You entered: %d\n", input);
	return EXIT_SUCCESS;
}

E.g., repeat asking for integers until user inputs 0, then print sum of all inputs.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int input = 0;
    int sum = 0;
    do {
        printf("Input an integer: ");
        scanf("%d", &input);
        sum += input;
    } while (input != 0);
    printf("Sum: %d\n", sum);
    return EXIT_SUCCESS;
}

Do while is sometimes neater than while
E.g., variable that needs to be equal to something in while expression doesn't have to be assigned a value using do {} while {}.