1 Decision Making if (score<40) { printf(“Fail\n”); }else { 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 /* shorthand version of if else statement */ (score<40) ? printf (“Fail\n”) : printf(“Pass\n”);
2 …. 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 */ } switch…case Multiple Selection Structure Consider creating a selection menu 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?
3 …. 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; } switch…case Multiple Selection Structure Let’s see how switch..case statement can help... Isn’t it looks much better?
4 switch…case Multiple Selection Structure Flowchart of the switch structure true false case a case a action(s)break case b case b action(s)break false case z case z action(s)break true default action(s)
5 …. 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”); } switch…case Multiple Selection Structure Guess what’s the output of this program…. Output Invalid Options!
6 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!’
7 //Exercise Answer #include 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!"); }
8 …. int counter; counter = 0; while (counter<5) { printf(“%d, “,counter); counter = counter + 1; } While Repetition/Loop Structure Guess what’s the output of this program…. Output 0, 1, 2, 3, 4
9 While Repetition/Loop Structure 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 ‘}’) true Loop continuation test Statement 1 Statement 2... false WHILE LOOP
10 …. int counter = 1, fact=1, n=4; while (counter<=n) { fact = fact * counter; counter = counter + 1; } printf(“ %d factorial is %d\n”, n, fact); While Repetition/Loop Structure Exercises – What’s the output? Output 4 factorial is 24
11 …. int counter = 0, row=3, col; while (counter<row) { col = 0; while (col<(counter+1)) { printf(“*”); col = col + 1; } printf(“\n”); counter = counter + 1; } While Repetition/Loop Structure Exercises – What’s the output? Output * ** ***
12 …. 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; } While Repetition/Loop Structure Exercises – What’s the output? Output ****
13 …. int counter; counter = 0;//counter initialisation while (counter<5) {//repetition condition checking printf(“%d, “,counter); counter = counter + 1;//counter increment } While Repetition/Loop Structure The earlier examples are typical Counter-controlled repetition structure. 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….
14 …. int score=0; while (score >= 0) { printf(“Enter a score [enter negative score to exit]: “); scanf(“%d”,&score); } While Repetition/Loop Structure Can you tell how many loops there will be? 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
15 …. 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 Let’s use it to count the number of digits that form the input integer
16 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. While Repetition/Loop Structure Another example Can u tell what’s the sentinel value in the above while loop?
17 float balance, monthly_interest, monthly_interest_rate, monthly_instalment; int months = 0; balance = ; 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
18 While Repetition/Loop Structure Exercises 1.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 2.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 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 ]
19 …. int counter; counter = 1; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<4); do...while Repetition/Loop Structure Guess what’s the output of this program…. Output 1, 2, 3,
20 do...while Repetition/Loop Structure do { statement 1 statement 2 …... } (loop continuation test); //statement to executed after exiting the while loop 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 ‘}’) true Loop continuation test Statement 1 Statement 2... false DO..WHILE LOOP
21 …. int counter; counter = 3; do { printf(“%d, “,counter); counter = counter + 1; } while (counter<1); do...while Repetition/Loop Structure Exercise: What’s the output? Output 3
22 …. int counter; counter = 3; do printf(“%d, “,counter); counter = counter + 1; while (counter<1) do...while Repetition/Loop Structure Exercise: Any syntax error? 1. The braces {} 2. The semicolon ; { } ;
23 counter = 3; do counter = counter + 1 while (counter<1); do...while Repetition/Loop Structure Consider this example... When there is only one statement, it can be written as do statement while (expression); Note that no semicolon is required at the end of statement.
24 int score; printf (“Enter a negative score to exit\n“); do { printf (“Enter a score: “); scanf(“%d”, &score); } while (score>=0); do...while Repetition/Loop Structure Any difference in the output of the programs? int score; printf (“Enter a negative score to exit\n“); while (score>=0) { printf (“Enter a score: “); scanf(“%d”, &score); } do…while will go into the loop at least once while might not go into the loop at all.
25 int i; for (i=0; i<5; i=i+1) { printf(“%d, “,i); } for Repetition/Loop Structure Guess what’s the output of this program…. Output 1, 2, 3, 4, int i; i = 0; while (i<5) { printf(“%d, “,i); i = i + 1; } Exactly the same as this program except on the way of writing it only
26 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.
27 int i; for (i=4; i>0; i=i-1) { printf(“%d, ”, i); } for Repetition/Loop Structure Exercise: What’s the output? Output 4, 3, 2, 1 int row, col; for (row=0; row>2; row=row+1) { for (col=0; col>3; col=col+1) { printf(“*”); } printf(“\n”); } Output * ** *** Nested for structure
28 for Repetition/Loop Structure Exercise: Any syntax errors? int i; for (i=4 i>0 i=i-1;) { printf(“%d, ”, i); } 1. Missing semicolon ; 2. No semicolon at the end of counter modification Anything wrong with this program logically? int i; for (i=4 i>0 i=i+1;) { printf(“%d, ”, i); } Infinite loop (System Hang) This is called Run-time error. The program will still run except that the result is something undesired Hence, You Must Learn How To Debug Your Program!
29 Exercises 1.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.
30 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. * *** ***** *** *
31 Exercises Answers //No. 1 #include 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); }
32 Exercises Answers //No. 2 #include 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); }
33 Exercises Answers //No. 3 include 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"); }