140 likes | 153 Views
Understand while, for, do-while loops in C# with syntax and examples. Learn how to iterate until a condition or flag is met, and work with nested loops. Improve your programming skills with practical exercises.
E N D
CS 105 Lecture 7 For & Do-While Loops Sun, Feb 27, 2011, 2:16 pm
Exam 1 • 16 Scores: • 91 88 88 88 85 82 76 75 74 73 71 71 • 67 62 47 43 • Avg 73.8 • Std dev 14.1
The while Loop • Syntax • while (condition) statement; • With multiple statement body: • while (condition) { statement; statement;}
The for Loop • Syntax: • for (expression1; condition; expression2) statement; • for (expression1; condition; expression2){ • statement; • statement; • } • Same as: • expression1;while (condition){ statement; expression2;}
Example for Loop • int numEmployees,curNum; • cout << “Enter Number of Employees: “; • cin >> numEmployees; • if (numEmployees > 0) • { • for (curNum = 0; curNum < numEmployees; curNum++) • { • cout << “Welcome to CorpLand!” << endl; • } • } • else • { • cout << "Egads!! Negative number of employees??" << endl; • }
Looping for Input • char letterEntered = ‘A’; • while (letterEntered != ‘Z’) • { • cout << “Enter a letter: “; • cin >> letterEntered; • }
Looping for Input • char command; • cout << "Welcome to our program!!" << endl • << "We'll process a sequence of commands" • << endl << "Enter command (or Q to quit): "; • cin >> command; • while (command != 'Q') • { • // ... do stuff for this command ... • cout << “Enter command (or Q to quit): “; • cin >> command; • }
Looping until Flag • boolean noMoreData(); • boolean done = false; • … • while (!done) • { • … • // do a bunch of stuff • … • if (noMoreData() == true) • done = true; • } • cout << “We’re all through – thank you!”
Nested Loops • int i, j; • for (i=0; i < 5; i++) • { • for (j=0; j < 6; j++) • { • cout << i << j << “ “; • } • cout << endl; • }
Nested Loops • int i, j; • for (i=0; i < 5; i++) • { • for (j=0; j < i; j++) • { • cout << i << j << “ “; • } • cout << endl; • }
Do-while Loop • Syntax • do statement;while (condition); • do{ statement; statement;}while (condition);
do-while Example • int inputNum = 0; • do • { • // ... do something with inputNum ... • cout << “Please Input Number, –1 to quit: “; • cin >> inputNum; • } • while (inputNum != -1);
What Is This? • while (stringEntered != “apple”) • { • cout << “Enter a red fruit: “; • cin >> stringEntered; • } • while (stringEntered != “banana”) • { • cout << “Enter a yellow fruit: “; • cin >> stringEntered; • } • while (stringEntered != “pomegranate”) • { • cout << “Enter a random fruit: “; • cin >> stringEntered; • }
What Is This? • for (i = 0; i < 10 ; i++) • cout << “Interesting, isn’t it?” << endl; • while (answer != ‘D’) • { • cout << “Enter an answer: “; • cin >> answer; • } • while (answer != ‘D’) • { • cout << “Enter an answer: “; • cin >> answer; • }