330 likes | 452 Views
Decision Making if (score<40) { printf(“Fail<br>”); } else { printf(“Pass<br>”); }. /* shorthand version of if else statement */ (score<40) ? printf (“Fail<br>”) : printf(“Pass<br>”);.
E N D
Decision Making if (score<40) { printf(“Fail\n”); } else { printf(“Pass\n”); } /* shorthand version of if else statement */ (score<40) ? printf (“Fail\n”) : printf(“Pass\n”); Not recommended in practice since it does not follow general fashion of programming language; other language does not offer this shorthand. Also because only ONE statement is allowed for each condition (not much use practically) Might be useful in understanding other people’s coding
switch…case Multiple Selection Structure Consider creating a selection menu …. printf(“Game Menu\n”); printf(“1 – Star Craft 2 – Red Alert 3 – War Craft\n”); printf(“Enter your selection:”); scanf(“%d”,&choice); if (choice==1) { /* Lauch Star Craft */ } else { if (choice==2) { /* Lauch Red Alert */ } else { /* Lauch War Craft */ } } What if there are 10 options or more? The if…else statement would have to be nested for 10 levels or more. It doesn’t seems like a neat solution, does it?
switch…case Multiple Selection Structure Let’s see how switch..case statement can help... …. printf(“Enter your selection:”); scanf(“%d”,&choice); switch(choice) { case 1: /* Launch Star Craft */ break; case 2: /* Launch Red Alert */ break; case 3: /* Launch War Craft */ break; } Isn’t it looks much better?
switch…case Multiple Selection Structure case z action(s) case a action(s) case b action(s) break break break default action(s) case z case b case a • Flowchart of the switch structure true false true false . . . true false
switch…case Multiple Selection Structure Guess what’s the output of this program…. …. int choice = 0; switch(choice) { case 1: printf(“Launching Star Craft\n”); break; case 2: printf(“Launching Red Alert\n”); break; case 3: printf(“Launching War Craft\n”); break; default: printf(“Invalid Options!\n”); } Output Invalid Options!
switch…case Multiple Selection Structure Exercise 1. Create a program that read in an integer from user. The value range from 0 to 9. Next, print out the value in Bahasa Malaysia. Example, if user input 7, the output is ‘Tujuh’. If user input any value not within the range, display message: ‘Jangan nakal-nakal…nanti Sir rotan!’
//Exercise Answer #include <stdio.h> main() { int number; printf("Please enter a number: "); scanf ("%d", &number); switch(number) { case 0: printf("Sifar"); break; case 1: printf("Satu"); break; case 2: printf("Dua"); break; case 3: printf("Tiga"); break; case 4: printf("Empat"); break; case 5: printf("Lima"); break; case 6: printf("Enam"); break; case 7: printf("Tujuh"); break; case 8: printf("Lapan"); break; case 9: printf("Sembilan"); break; default: printf("Jangan nakal nakal, nanti sir rotan!"); } }
While Repetition/Loop Structure Guess what’s the output of this program…. …. int counter; counter = 0; while (counter<5) { printf(“%d, “,counter); counter = counter + 1; } Output 0, 1, 2, 3, 4
While Repetition/Loop Structure false Loop continuation test WHILE LOOP true Statement 1 Statement 2 ... while (loop continuation test) { statement 1 statement 2 …... } //statement to executed after exiting the while loop If the loop continuation test is TRUE, the statements within the braces { } will be executed. When it reach the point right before ‘}’ , it will return to the beginning of the loop and repeat the process. if FALSE, exit the loop (go to first statement after ‘}’)
While Repetition/Loop Structure Exercises – What’s the output? …. int counter = 1, fact=1, n=4; while (counter<=n) { fact = fact * counter; counter = counter + 1; } printf(“ %d factorial is %d\n”, n, fact); Output 4 factorial is 24
While Repetition/Loop Structure Exercises – What’s the output? …. int counter = 0, row=3, col; while (counter<row) { col = 0; while (col<(counter+1)) { printf(“*”); col = col + 1; } printf(“\n”); counter = counter + 1; } Output * ** ***
While Repetition/Loop Structure Exercises – What’s the output? …. int counter=0, row=3, counter2, col=4; while (counter<row) { counter2 = 0; while (counter2<col) { printf(“*”); counter2 = counter2 + 1; } printf(“\n”); counter = counter + 1; } Output **** **** ****
While Repetition/Loop Structure The earlier examples are typical Counter-controlled repetition structure. …. int counter; counter = 0; //counter initialisation while (counter<5) { //repetition condition checking printf(“%d, “,counter); counter = counter + 1; //counter increment } Counter-controlled repetition is a definite repetition: number of repetition is known before loop start. while statement is seldom used for this type of repetition; for statement is more popular. (Discuss later) while statement is catered for another type of repetition….
While Repetition/Loop Structure Can you tell how many loops there will be? …. int score=0; while (score >= 0) { printf(“Enter a score [enter negative score to exit]: “); scanf(“%d”,&score); } This is a Sentinel-controlled repetition: number of repetition is UNKNOWN. The sentinel value (in this case, a negative score) shall indicate the termination of the loop
While Repetition/Loop Structure Let’s use it to count the number of digits that form the input integer …. int number, total_digit=0, divider=1; printf(“Please enter a decimal number”); scanf(“%d”, &number); while ((number/divider) != 0) { total_digit=total_digit + 1; divider = divider * 10; } printf(“There are %d digit in %d\n”,total_digit, number);
While Repetition/Loop Structure Another example Ali took a RM100,000 house loan from bank. The interest rate is 8% per annum, compound monthly. The monthly instalment is RM 700. Write a program to find out how long (in years & months) Ali need to fully settle his loan. Can u tell what’s the sentinel value in the above while loop?
While Repetition/Loop Structure float balance, monthly_interest, monthly_interest_rate, monthly_instalment; int months = 0; balance = 100000; monthly_interest_rate = (8.0/100.0)/12.0; while (balance>0.0) { monthly_interest = monthly_interest_rate * balance; balance = balance + monthly_interest - monthly_instalment; months = months + 1; } printf (“%d years %d months\n”, months/12, months%12);
While Repetition/Loop Structure Exercises • Write a program that reads a positive integer n and then computes and prints the sum of all integers from 1 to n and divisible by 3 • Write a program that interactively reads test score values until a negative test score is entered and then computes and outputs the average test score. The test score must be validated to ensure that they are between 0 and 100. • Write a program that accepts a positive integer and determines whether it is a numerical palindrome (a number that is the same forward and backward, such 13431) [BONUS]
do...while Repetition/Loop Structure Guess what’s the output of this program…. …. int counter; counter = 1; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<4); Output 1, 2, 3,
do...while Repetition/Loop Structure Loop continuation test Statement 1 Statement 2 ... do { statement 1 statement 2 …... } (loop continuation test); //statement to executed after exiting the while loop DO..WHILE LOOP true false Execute the statements within the braces { }. When it reach the end of the segment, it will perform the loop continuation test. If TRUE, it will return to the beginning of the loop and repeat the process. if FALSE, exit the loop (go to first statement after ‘}’)
do...while Repetition/Loop Structure Exercise: What’s the output? …. int counter; counter = 3; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<1); Output 3
do...while Repetition/Loop Structure Exercise: Any syntax error? …. int counter; counter = 3; do printf(“%d, “,counter); counter = counter + 1; while (counter<1) 1. The braces {} 2. The semicolon ; { } ;
do...while Repetition/Loop Structure Note that no semicolon is required at the end of statement. Consider this example... counter = 3; do counter = counter + 1 while (counter<1); When there is only one statement, it can be written as dostatementwhile (expression);
do...while Repetition/Loop Structure int score; printf (“Enter a negative score to exit\n“); do { printf (“Enter a score: “); scanf(“%d”, &score); } while (score>=0); Any difference in the output of the programs? do…while will go into the loop at least once while might not go into the loop at all. int score; printf (“Enter a negative score to exit\n“); while (score>=0) { printf (“Enter a score: “); scanf(“%d”, &score); }
for Repetition/Loop Structure Guess what’s the output of this program…. int i; for (i=0; i<5; i=i+1) { printf(“%d, “,i); } int i; i = 0; while (i<5) { printf(“%d, “,i); i = i + 1; } Output 1, 2, 3, 4, Exactly the same as this program except on the way of writing it only
for Repetition/Loop Structure for (initializations; loop continuation test; counter modifications) { block of statements } //statement to executed after exiting the for loop 1. Perform the initializations (if any) 2. Perform loop continuation test. (if any) 3. If FALSE, exit the loop (go to first statement after ‘}’). 4. If TRUE, the statements within the braces { } will be executed. 5. When it reach the point right before ‘}’ , it will return to the beginning of the loop, perform counter modification (if any) 6. Repeat step 2.
for Repetition/Loop Structure Output 4, 3, 2, 1 Output * ** *** Exercise: What’s the output? int i; for (i=4; i>0; i=i-1) { printf(“%d, ”, i); } int row, col; for (row=0; row>2; row=row+1) { for (col=0; col>3; col=col+1) { printf(“*”); } printf(“\n”); } Nested for structure
for Repetition/Loop Structure 1. Missing semicolon ; 2. No semicolon at the end of counter modification • Infinite loop (System Hang) • This is called Run-time error. • The program will still run except that the result is something undesired Exercise: Any syntax errors? int i; for (i=4 i>0 i=i-1;) { printf(“%d, ”, i); } Anything wrong with this program logically? int i; for (i=4 i>0 i=i+1;) { printf(“%d, ”, i); } Hence, You Must Learn How To Debug Your Program!
Exercises Ah Beng save RM500 in his bank account every year and the bank pay him interest of 4% per annum on daily compound basis. Write a program that will calculate the balance of his account at a specific period of saving in year basis. Use for loop to solve this problem. 2. Write a program that can take in a series of number of any length specified by user and find out the smallest and the largest number in the series. Use for loop to solve this problem.
Exercises 3. Write a program that prints the following diamond shape. You may use printf statements that print either a single asterisk (*) or a single space. Maximize you use of repetition (with nested for structures) and minimize the number of printf statement. * *** ***** *** *
//No. 1 #include <stdio.h> main() { int number_of_year, counter_year, counter_day; double daily_interest, balance; printf("Enter the number of years: "); scanf("%d", &number_of_year); balance = 0; counter_year = 0; for (counter_year=0; counter_year<number_of_year; counter_year++) { balance = balance + 500; for (counter_day = 0; counter_day<365; counter_day++) { daily_interest = balance * (0.04/365); balance = balance + daily_interest; } } printf("The balance after %d years is $%.2lf\n", number_of_year, balance); } Exercises Answers
//No. 2 #include <stdio.h> main() { int series_length, number, min, max, counter; printf("Enter the length of the series: "); scanf("%d", &series_length); counter = 1; printf("Enter number no.%d: ", counter); scanf("%d", &number); max = number; min = number; for (counter=2; counter<=series_length; counter++) { printf("Enter number no.%d: ", counter); scanf("%d", &number); if (min>number) { min = number; } if (max<number) { max = number; } } printf("The minimum is %d and the maximum is %d\n", min, max); } Exercises Answers
//No. 3 include <stdio.h> main() { int cnt_space, cnt_ast, cnt_row; for (cnt_row=1; cnt_row<=3; cnt_row++) { for (cnt_space=1; cnt_space<=3-cnt_row; cnt_space++) { printf(" "); } for (cnt_ast=1; cnt_ast<=cnt_row; cnt_ast++) { printf("*"); } for (cnt_ast=cnt_row-1; cnt_ast>=1; cnt_ast--) { printf("*"); } printf("\n"); } for (cnt_row=2; cnt_row>=1; cnt_row--) { for (cnt_space=1; cnt_space<=3-cnt_row; cnt_space++) { printf(" "); } for (cnt_ast=1; cnt_ast<=cnt_row; cnt_ast++) { printf("*"); } for (cnt_ast=cnt_row-1; cnt_ast>=1; cnt_ast--) { printf("*"); } printf("\n"); } } Exercises Answers