170 likes | 283 Views
Chapter 4 – do while. “If you're afraid - don't do it, - if you're doing it - don't be afraid!” ― Genghis Khan. Quiz. Write a program that tests whether an integer is even or odd. //program that tests whether an integer is even or odd #include < stdio.h > int main(){ int n=0;
E N D
Chapter 4 – do while “If you're afraid - don't do it, - if you're doing it - don't be afraid!” ― Genghis Khan
Quiz • Write a program that tests whether an integer is even or odd.
//program that tests whether an integer is even or odd #include <stdio.h> int main(){ int n=0; printf("Please enter the number to check \n:"); scanf("%d",&n); if((n % 2) == 0){ printf("Number %d is Even \n:",n); } else { printf("Number %d is Odd \n:",n); } system("pause"); return 0; }
Assume pow() function in <math.h> doesn't exist...). inti,result= 1; int base=2; int power=3; for (i=0; i<power; i++) { result *= base; }
The do…while Repetition Statement • The do…while repetition statement • Similar to the while structure • Condition for repetition tested after the body of the loop is performed • All actions are performed at least once • Format: do { statement; } while (condition );
The do…while Repetition Statement • Example (letting counter = 1): do { printf( "%d ", counter ); } while (++counter <= 10); • Prints the integers from 1 to 10
The break and continue Statements • break • Causes immediate exit from a while, for, do…while or switch statement • Program execution continues with the first statement after the structure • Common uses of the break statement • Escape early from a loop • Skip the remainder of a switch statement
Break Statement Example • 1 2 3 4 • Broke out of loop at x == 5
The break and continue Statements • continue • Skips the remaining statements in the body of a while, for or do…while statement • Proceeds with the next iteration of the loop • while and do…while • Loop-continuation test is evaluated immediately after the continue statement is executed • for • Increment expression is executed, then the loop-continuation test is evaluated
Logical Operators • && ( logical AND ) • Returns true if both conditions are true • || ( logical OR ) • Returns true if either of its conditions are true • ! ( logical NOT, logical negation ) • Reverses the truth/falsity of its condition • Unary operator, has one operand • Useful as conditions in loops Expression Result true && false falsetrue || false true !false true
Assign – 3: Count letters, digits and others from input • Input Letters case range (‘A’………’Z’) • Example ‘A’ <= input , input<='Z' • Input lower case Letters range (‘a’…..’z’) • Input digits range (‘0’….’9’) printf("Enter Numbers Digits and Others:\n"); while( (c=getchar( )) != '\n' ) Hint : Use && And || in this program