//* How long to stay in a loop - 4 examples *

// How long to stay in a loop: loop type #1 #include <stdio.h> int main() { int cnt; double sum=0.0; // remember to initialize the sum printf("Please enter the number of data items "); scanf("%d", &cnt); // read number of numbers printf("Please enter the data one by one:" << endl; for (int i=1; i<=cnt; i++) { double x; scanf("%lf", &x); // read next number available sum+=x; } printf("The average number is %lf\n", sum/cnt); return(0); } // How long to stay in a loop: loop type #2 #include <stdio.h> int main() { int cnt=0; // remember to initialize the count double sum=0.0; // remember to initialize the sum printf("Please enter the data one by one followed by a negative number:\n"); for (;;) { double x; scanf("%lf", &x); // read next number available if (x<0) break; sum+=x; cnt++; } // break goes here printf("The average number is %lf\n", sum/cnt); return(0); } // How long to stay in a loop: loop type #3 #include <stdio.h> int main() { int cnt=0; // remember to initialize the count double sum=0.0; // remember to initialize the sum for (;;) { printf("Please enter the next data item: "); double x; scanf("%lf", &x); // read next number available sum+=x; cnt++; char ch; printf("Continue? (y/n)"); scanf("%c", &ch); if (ch=='n') break; // single character goes in single quotes - 'n' } // break goes here printf("The average number is %lf\n", sum/cnt); return(0); } // How long to stay in a loop: loop type #4 #include <stdio.h> int main() { int cnt=0; // remember to initialize the count double sum=0.0; // remember to initialize the sum printf("Please enter the data one by one followed by a letter q:\n"); for (;;) { double x; int r; r = scanf("%lf", &x); // read next number available if (r==0 || r==EOF) break; // exit if non-numeric data encountered - read failed sum+=x; cnt++; } // break goes here printf("The average number is %lf\n", sum/cnt); return(0); }