1 / 42

Review

Review. CHAPTER 1 Structured Programming II. Iterations (Loops). In C there are three iteration structures: while Loops do while Loops for loops WHILE LOOPS: while (condition) { loop body }

clees
Download Presentation

Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review CHAPTER 1 Structured Programming II

  2. Iterations (Loops) • In C there are three iteration structures: • while Loops • do while Loops • for loops WHILE LOOPS: while (condition) { loop body } Note that, iterations continue while condition is TRUE and stopped when condition is FALSE.

  3. Iterations (Loops) DO … WHILE LOOPS: do { loop body } while (condition) Not that, in do … while loops, it is guaranteed that at least one execution of the loop body, even the condition is not TRUE. FOR LOOPS: for (loop initialization; loop test; loop adjustment) { loop body } Note that, if the number of iterations are underestimate on design time, the for loop is the best alternative.

  4. Iterations (Loops) Exercises: ex1) i=1; sum=0; while (i<10) { sum+=i; i++; } printf(“%d”,sum); ex2) i=10; sum=0; do { sum+=i; i++; } while (i<10) printf(“%d”,sum);

  5. Iterations (Loops) Exercises: ex3) sum=0; for (i=0; i<10; i++) { sum+=i; } printf(“%d”,sum);

  6. Nested Loops • Using a loop within another loop is termed as NESTED LOOP. Example : for (i=0; i<10; i++) { for (j=0; j<=i; j++) { printf(“*”); } }

  7. Infinite Loops • Never ended loops are termed as INFINITE LOOPs. Example : Ex1) ch=‘ ‘; while !(ch==‘Y’|| ch==‘y’|| ch==‘N’|| ch==‘n’) { clrscr(); printf(“\nEnter your choice (Y/N) : “); ch=getch(); } This loop can be ended with entering either ‘Y’,’y’ or ‘N’,’n’.

  8. Infinite Loops Ex2) ch=‘ ‘; for(;;) { clrscr(); printf(“\nEnter your choice (Y/N) : “); ch=getch(); if (ch==‘Y’|| ch==‘y’|| ch==‘N’|| ch==‘n’) break; //ends the infinite loop. } This loop also can be ended with entering either ‘Y’,’y’ or ‘N’,’n’. Notice that, in both of the examples, the iteration time is unknown at design time, and loops can be conditionally ended at run time.

  9. Conditional Statements IF Statement : If (conditional-expression) { true_part } else { false_part } example: if (num%2==0) printf(“\n %d is an even number”,num); else printf(“\n %d is an odd number”,num);

  10. Conditional Statements SWITCH ... CASE Statement : switch (integer expression) { case case_value_1: statement_body_1; case case_value_2: statement_body_2; ... case case_value_n: statement_body_n; default : statement_body_else_case } switch … case statement can be used only for equality checks, it is not suitable for range checks.

  11. Conditional Statements Example : switch (choice) { case ‘Y’: case ‘y’: printf(“\n You said YES !”); break; case ‘N’: case ‘n’: printf(“\n You said NO !”); break; } Note that, the statement body is ended with break statement and the control is carried to the out of switch statement!

  12. Nested If Statements Example : if (age < 18) { if (gender == “male”) printf(“\n You are a BOY ”); else printf(“\n You are a GIRL”); } else if (gender == “male”) printf(“\n You are a MAN ”); else printf(“\n You are a WOMAN); }

  13. Arrays • An ARRAY is a collection of a fixed number of objects all of the same type, which are stored sequentially in computer memory. • The objects in an array are array’s elements. • The number of elements in an array is the array size. • The common type of array’s elements is the array type. • Before use an array, you have to declare it first. Array Declaration: array_type array_name [ array_size ]

  14. Arrays Examples : ex1) double rate [5]; ... rate[0] = 0.075; rate[1] = 0.080 rate[2] = 0.082; rate[3] = 0.085; rate[4] = 0.088; printf(“\n support fund amount is %f”, gross * rate[3]); … ex2) char grades [5] {‘F’, ‘D’, ‘C’, ‘B’,’A’}; int mark = 3; ... printf(“You got %c !”,grades[mark]); ...

  15. Multidimensional Arrays • You can declare matrix (two dimensional) or cube (three dimensional) arrays just like declaring lists (one dimensional arrays). ex1) /* A matrix */ int i, j; int class_grades[2][5] {50, 56, 87, 67, 98, 70, 81, 46, 93, 55} ; /* 2 courses for 5 students */ for (i=0; i< 2; i++) { printf(“\n”); /* Jump to a new line on each new course */ for (j=0;j<5; j++) { printf(“ student:%3d, mark:%3d”, j+1,class_grade[i][j]; } }

  16. Multidimensional Arrays ex2) /* A cube */ main() { int i, j,k; int student_grades[2][5][3] {50, 56, 87, 67, 98, 70, 81, 46, 93, 55, ...} ; /* 2 courses for 5 students and 3 quizzes */ for (i=0; i< 2; i++) { printf(“\n”); /* Jump to a new line on each new course */ for (j=0;j<5; j++) { printf(“\n”); /* Jump to a new line on each new course */ for (k=0;k<3;k++) { printf(“ student:%d, course:%d”, quiz%d: %d”, i, j, k, student_grade[i][j][k]); } } } }

  17. What is a Function? • A function is a module that performs its task when it called. • It may accept a set of values called “parameters” when it called. • Functions may returns one or no value back (the value is returned back to the program or another function which called this function). • All C programs must contain the function main().

  18. Modular Design with Functions Main() function_01() function_02() function_03() printf() scanf() Print_10Xs() User Defined Function Standard Library functions Requires #include <stdio.h>

  19. How Functions are Worked? • The code of a function is not a part of main. ex. The actual code of the function printf is not existing in the main(). • The source code of the user-defined functions can be in the same file together with the main(). • In some projects, user may need to combine all user-defined function in the external files to make his/her own library. User-defined libraries have to be included as predefined libraries, like stdio.h, conio.h.

  20. Functions and main() In The Same File. File Main() { … } Function_01() { … }

  21. How Functions are Worked? • Functions may require: • One • More then one • No arguments (parameters) to perform their tasks. • Arguments are used inside parentheses. Function_name (argument_01, argument_02,…) • Arguments are separated from each other with comas (‘,’).

  22. How Functions are Worked? • When a function is called within main(), the execution control will be transferred to the part where the called function’s actual code is existing. • When the function completes its task, the execution control is returned back to the main(). • The input values that a program sends into to the called function are ARGUMENTS. • The value that is send back from the function is called RETURN VALUE.

  23. How Functions are Worked? • Just as variables must be declared before they are used, functions also have to be declared before they are called. • Functions are usually declared before main(), but this is not a rule. • When the function definition (the actual content) is placed before main(), the function declaration is not necessary.

  24. Function Declaration Format : return_type function_name( argument_type1, argument_type2, … argument_typen) ; Examples : int rect_area( int, int) ; double sales_tax(double, double); void print_char(char, int); void say_hello( void);

  25. Function Declaration • Set the function type to the void, when the declared function will not return any value. Example : void print_multichar(int, char); • If the declared function will not has any argument, again we have to use void at the position which the argument types are declared. Example : void print_10Xs( void);

  26. Function Definition • After the declaration, function must be defined. • The content of a function is written in its definition part. Format : return_type function_name( argument_type1 argument_name1, argument_type2 argument_name2, … argument_typen argument_namen) { function_body } Note that, there is no semi-colon (;) is used after the closed parentheses (at the end)!

  27. Function Definition Examples : int rect_area( int side1, int side2) { int area; area = side1 * side2; return area; } void print_char( int num, char ch) { int i; for(i=0;i<num;i++) print(“%c”,ch); }

  28. Function Definition Examples : void Print_10Xs( void) { int j; for(j=0; j<10; j++) print(‘X’); } char Read_choice( void) { char ch=‘q’; while !(ch==‘Y’|| ch==‘y’|| ch==‘N’|| ch==‘n’) { clrscr(); printf(“Enter your choice (Y/N) :”); ch= getch(); } return ch; }

  29. Function Types • No Argument, No Return Value : Ex : void Print_10Xs( void); • No Arguments, One Return Value: Ex : char Read_choice( void); • Some Arguments, No Return Value: Ex : void Print_Char(int, char); Some Arguments, One Return Value: Ex : double factorial( int);

  30. Applications With Functions • Problem 1: Write a program that displays the following patern on the screen. XXXXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXX • Problem 2: Write a program that will ask user to enter a character, and draw a triangular pattern (with 5 rows height) with using the character that the user entered.

  31. Applications With Functions Solution 1: # include <stdio.h> void Print_10Xs(void); /* Function Declaration */ void main() { int j; for (j=0; j<5; j++) { Print_10Xs(); printf(“\n”); } } /* end of the main()*/ void Print_10Xs( void) /* Function Definition*/ { int k; for (k=0; k<10; k++) printf(‘X’); } /* End of Function*/

  32. Applications With Functions Solution 2: # include <stdio.h> void Print_Char(int , char); void main() { char ch; int j; printf(“\n Enter a character to draw a triangle”); scanf(“%c”,&ch); for (j=0; j<5; j++) { Print_Char( j, ch); printf(“\n”); } } /* end of the main()*/ void Print_Char( int num, char ch) { int k; for (k=0; k<num; k++) printf(‘%c’,ch); } /* End of Function*/

  33. Passing Arguments by Value • When main() communicates with a function, it passes the value of an argument, not the arguments itself. Example : # include <stdio.h> int f_incement( int); void main() { int main_num = 5, func_num=8; func_num = f_increment(main_num); printf(“\n main_num = %d”,main_num); printf(“\n func_num = %d”,func_num); } int f_increment(int main_num) { main_num++; return main_num; }

  34. Passing Arguments by Value • When you execute the previous program, you will see that the value of the main_num will be preserved, while the value of func_num will be updated with the function return value. So the output will be: main_num = 5 func_num = 6

  35. Exercises #include <stdio.h> double sales_tax(double, double) void main() { double item_price, tax_rate, total_price; printf(“\n Enter the item price :”); scanf(“%lf”,&item_price); printf(“\n Enter the tax_rate :”); scanf(“%lf”,&tax_rate); total_price=sales_tax(item_price, tax_rate); printf(“Total Price = %f”, total_price); } /* End of main() */ double salex_tax( double price, double tax) { double result; result = price + price * tax; return result; } /* End of function*/

  36. Exercises #include <stdio.h> double value_pi(void) void main() { double radious, area; printf(“\n Enter the radious :”); scanf(“%lf”,&radious); area = value_pi() * radious * radious; printf(“The area of the circle is %f”, area); } /* End of main() */ double value_pi( void) { double result; result = 22 / 7; return result; } /* End of function*/

  37. Global & Local Variables GLOBAL VARIABLES • Any variable that is not declared within a function and main() is called GLOBAL VARIABLE. • Global variables can be accessed by main() and any function. • Global variables lives during the program run. • Global variables are used to keep some common values that are used and modified by main() and the functions. • There is no need to pass a global variable as an argument to a function.

  38. Global & Local Variables LOCAL VARIABLES • Any variable that is declared within a function or main() is called LOCAL VARIABLE. • Local variables only can be used at the module which, that are declared. • Local variables are not accessible for the modules out of their owner. • The life of a local variable is limited with the execution time of the module which they are declared in. • We can give the same name to Local variable when we declare them in DIFFERENT functions.

  39. Global & Local Variables Example 1 : # include <stdio.h> void func(void); int var_2=200; /* a global variable */ void main() { ++var_2; printf(“\n main result before func() : %d” , var_2); func(); ++var_2; printf(“\n main result after func() : %d” , var_2); } /* end of main()*/ void func( void) { ++var_2; printf(“\n main_result during func() %d”,var_2); }

  40. Global & Local Variables Sample Run : main_result before func() : 201 main_result during func() : 202 main_result after func() : 203

  41. Passing An Array To A Function # include <stdio.h> double avg( int[], int); void main() { int j, result[4]; for( j=0; j < 4; j++) { printf(“\n Enter the Quiz %d result :”, j+1); scanf(“%d”,&result[j]); } printf(“\n The average is %f” , avg(result, 4)); } /* end of main()*/ void avg (int arr[], int size) { int k, sum=0; for (k=0; k < size; ++k) sum += arr[k]; return (double) sum / size; }

  42. Passing An Array To A Function Sample Run : Enter the Quiz 1 Result : 60 Enter the Quiz 1 Result : 70 Enter the Quiz 1 Result : 80 Enter the Quiz 1 Result : 50 The average is 65

More Related