













































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
How to use for loops,while loops and do while loops in C
Typology: Lecture notes
1 / 53
This page cannot be seen from the preview
Don't miss anything!














































− Prepares data for the compiler/interpreter
− Two examples: #include directive #define directive
− Can be used for compile-time constants − Cannot be used for things that vary during program runtime. − Supports parameterized macros (more advanced usage)
#define PI 3.
● Poor code area = radius * radius * 3.14159; circumference = 2 * radius * 3.14159;
● Better code #define VAL_PI 3. ... area = radius * radius * VAL_PI; circumference = 2 * radius * VAL_PI;
− Makes code more readable − Easier to remember − Easier to maintain
− Input handling ● Ask for another input if user gave an invalid input ● Prompt user if they want to give another input
− Repetitive tasks ● Compute pay for several employees (same formula) ● Counting number of inputs
− Initialization ● The controlling variable must be initially set to a known valid state. − Testing (the loop repetition condition) ● An expression involving the controlling variable must be evaluated to determine if the loop will continue or not. − Update ● The controlling variable must be updated in a way that the loop repetition condition will eventually terminate the loop
initialization
loop body Update } − The loop repetition expression is evaluated to determine if the loop will execute the statement
i = 0; while (i <= 5) { i = i + 1; }
count_emp < 7
count_emp = 0
True
False Display “all employees processed”
Display pay
Input hours, rate
pay = hours*rate
count_emp = count_emp+
count_emp < 7
count_emp = 0
True
False Display “all employees processed”
Display pay
Input hours, rate
pay = hours*rate
count_emp = count_emp+
Initialization ;
while ( Test ) { body; Update ; }
for( Initialization ; Test ; Update ) { body; }
/* Double counters */ int main (void) { int x; int y;
for ( x=0, y=0; x<1000 && y<2000; x+=1, y+=2) { printf("%d \t %d\n", x, y); } return (0); }
− Columns are variables/expressions/conditions − Rows are loop iteration
i = 0; while (i <= 5) { printf("%3d %3d\n", i, 10-i); i = i + 1; }
● Standard Syntax:
initialization; do { Loop body update } while ( repetition condition );
● Loop body is executed at least once.
● Note the semicolon (;) at the end
do { printf("Enter the number 5: "); scanf("%d", &number); } while (number != 5);