for Keyword
Using for loops with Arrays
Output all the elements on the array.
Divide Each Element by 2
Can use while to achieve same target
Similar with using %s with printf and a char array:
Use ‘\0’ or 0 as ending point. Sometimes we need to use !=‘ ’ If it is required
while vs for:
for : know how many iterations is required
while: do not know the times of iterations.
Notice:
for loop can be written as an infinite loop as :
Printing an Array, Using a Loop:
Chose the number of elements in the array as the index to control the iteration of for loop
Printf the array from final to first:
Copying Between Arrays:
Copy from one array to another array in reverse:
Basic Searching:
How many elements in search_dataare greater than 25 :
The message array’s size:
Iterating a C-String:
Exercise:
Requirements (5x01a Number to Word switch)
Design
Declare a variable => printf(“input a number…”)=> scanf =>switich(number){case 0;case1;case2….;default}=> printf(“zero; one; ….; invalid”)
Implementation
Requirements (5x02a - Conditional Max of Two)
Design
Declare two variables=> printf(“first number”)=>scanf()=>printf(“second number”)=>scanf=> if(number1 > number2)=> printf(“…”);=> if(number2>1)=> printf(“…”).
Implementation
Test
Errors Encountered
When using the if and else:
Debugging:
Condition is wrong
Lessons Learnt:
Be care the condition inside the if or else if.
Requirements (5x03a - Count Up Loop)
Design
Declare a variable
=> for (i=40, i <= 400, ++i)
=> {printf(“…”);}
Implementation
Test
Requirements (5x04a - Simple Loop)
Design
Declare a variable =>printf(“n?”);=> scanf
=> for(int i =1; i<=n; ++i) =>{printf(“[…]”);}
Implementation
Test
Requirements (5x05a - Multiplication Table)
Design
Declare two variables => printf(“enter a number…”)=>scanf()=>printf(“the7 times…”)
=>for (int i=0; I<=14; ++I) => result =i*number; =>printf(“%d x %d = %d”, i, number, result)
Implementation
Test
Requirements (5x06a - Power Using a Loop)
Design
Declare three variables => printf(“enter the base”)=> scanf => printf(“enter the power”)=>scanf
=> printf(“…is the same as…”)=> printf(base)
=> for (int i =1; i<=(power-1); ++i) => {printf(“%d”, base)=> result *= base}
=> printf(“which is…”)
Implementation
Test
Errors Encountered
Debugging:
Should use variable rather the const number.
Lessons Learnt:
Should be care about if the number or variable should be used
Requirements (5x07a - ASCII Alphabet Printer)
Design
Printf(“a”);
=>Char alphabet_lowcase = ‘a’;
=>For (int i =1; i<=26; ++i) => alphabe_lowecase += i;=> printf(alphabe_lowcase)
Printf(“A”);
=>Char alphabet_upcase = ‘A’;
=>=>For (int i =1; i<=26; ++i) => alphabe_upecase += i; => printf(alphabe_upcase)
Implementation
Test
Errors Encountered & Debugging:
Because these variables are char, it cannot be calculated as int (by using ++ or +=)
Lessons Learnt:
The char cannot be calculated as int (by using ++ or +=), notice the type of char !
Requirements (5x08a - Fix This Loop)
Debugging
Implementation
Test