syntax: while (expression) A condition that is true or false stmt Body. {} compound statementsemantics: Evaluate expression, if true execute the statements of the body and then re-execute the while statement.
//read numbers from user, output the square root. 0 to quit cout << "Enter nos. for sqr. rooting. 0 to quit: "; cin >> num; //first number user enters. "priming" read while (num != 0) { //until number entered is a 0 cout << sqrt(num) << endl; cin >> num; //next number user enters } ------------------------------------------------------- //same, but check for negative numbers cout << "Enter nos. for sqr. rooting. 0 to quit: "; cin >> num; while (num != 0) { if (num > 0) //body of any statement can contain any statements cout << sqrt(num) << endl; else cout << "No square root of negative number."; cin >> num; } ------------------------------------------------------- //input 5 numbers from user and sum them sum = 0; //initialize the sum to 0 count = 0; //count of number of numbers read while (count < 5) { //loop five times cin >> num; sum += num; //add num to sum; short for sum = sum + num count++; //increment counter of numbers } cout << "Sum is " << sum; ------------------------------------------------------- //user tells how many numbers to input and sum cout << "Enter number of numbers: "; cin >> num_nums; sum = 0; count = 0; while (count < num_nums) { //loop num_nums times cin >> num; sum += num; count++; } cout << "Sum is " << sum; ------------------------------------------------------- //input numbers from user. Negative number indicates end. sum = 0; //no need for count variable cin >> num; //first number from user while (num >= 0) { //until a negative number is entered sum += num; cin >> num; } cout << "Sum is " << sum;if the first number entered is negative, the condition is false the first time in the while statement, thus the body wouldn't be executed even once.
A while loop will execute 0 or more times.
//determine the number of digits in an integer //Ex. 548 has 3 digits, 2974 has 4 digits cout << "Enter an integer: "; cin >> num; digits = 0; while (num > 0) { num = num / 10; //integer divide by 10 digits++; } cout << "Number of digits is " << digits; Trace this code with some examples. Show the values of the variables that result from execution of each statement. Does it work with negative number? How to correct it? ---------------------------------------- //read chars until #, //count numbers of lowercase letters and of uppercase letters //and of all other chars int lowers=0, uppers=0, others=0; char c; cin >> c; while (c != '#') { //until # is entered if (islower(c)) //c is one of 3 categories lowers++; else if (isupper(c)) uppers++; else others++; cin >> c; } cout << "Number of lower letters: " << lowers << endl; cout << "Number of upper letters: " << uppers << endl; cout << "Number of all other chars: " << others << endl;
Next (logical operators)