0% found this document useful (0 votes)
3 views

chapter2_4

Chapter 4 covers control flow in C programming, focusing on control structures such as selection (if, if-else, switch) and repetition (for, while, do-while). It provides examples of each structure, including practical applications like calculating the area of a triangle and determining leap years. Additionally, it discusses loop interruption using break and continue statements.

Uploaded by

hanhihd3095
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chapter2_4

Chapter 4 covers control flow in C programming, focusing on control structures such as selection (if, if-else, switch) and repetition (for, while, do-while). It provides examples of each structure, including practical applications like calculating the area of a triangle and determining leap years. Additionally, it discusses loop interruption using break and continue statements.

Uploaded by

hanhihd3095
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter 4

The control flow


Contents

3.1. C control structures


3.2. Selection
3.3. Repetition

2
3.1. C control structures

• Selection
if
if . . . else
switch

• Repetition
for loop
while loop
do . . . while loop

3
Selection

• if statement
• if … else statement
• switch statement

4
If statement

if (expression) statement
If the condition is true (value of expression is 1 or nonzero)
the statement is executed

5
If … else statement

if (expression) statement1 else statement2


If the condition is true (value of expression is 1 or
nonzero),statement1 is executed. Otherwise
statement2 is executed

6
Condition: expression

Any expression is valid. But logical expessions are more


popular
Logical expressions may include:

6 Relational Operators
< <= > >= == !=
3 Logical Operators
! && ||

7
Example 1

• Write a program to compute area of a triangle, given


its three sizes with triangle inequality checking.
• Triangle inequality
• The sum of the lengths of any two sides of a triangle is
greater than the length of the remaining side.

8
Program
1. #include <stdio.h>
2. #include <math.h>
3. main()
4. {
5. float a,b,c,s,A;
6. printf("\nEnter three sizes of the triangle, a,b,c:");
7. scanf("%f %f %f", &a,&b,&c);
8. if (a>0 && b>0 && c>0 && a+b>c && a+c>b && b+c>a)
9. {
10. s=(a+b+c)/2;
11. A= sqrt(s*(s-a)*(s-b)*(s-c));
12. printf ("\nArea of the triangle: %1.2f",A);
13. }
14. else
15. printf("\nNot a triangle!");
9
16. }
Example 2

• Check whether the year you enter is a leap year or not


• In the Gregorian calendar, A leap year is a year
containing one extra day (366 days)
• Most years that are evenly divisible by 4 are leap years
• Years are evenly divisible by 100 are not leap year unless
they are evenly divisible by 400

10
Example 3

• Write a program to find all the roots of a quadratic equation ax2+bx+c=0


• User interface

• What happen if the user type 0,0,1 or even 0,0,0?

11
Program
1. #include <stdio.h>
2. #include<conio.h>
3. #include <math.h>
4. main()
5. { float a, b, c, delta, x1,x2;
6. puts("Enter coefficients a b c : ");
7. scanf("%f%f%f", &a, &b, &c);
8. if( a==0)
9. {printf("Equation is not quadratic.Become linear equation %fx+%f=0",b,c);
10. if(b==0)
11. if (c!=0)puts ("Inconsistent liner equation. No root.");
12. else puts ("Every number is a root of the equation!");
13. else printf ("\nThe unique root of linear equqtion: x= %f",-c/b);
14. }
15. else
16. {delta=b*b-4*a*c;
17. if (delta < 0)
18. puts("");
19. else
20. if (delta == 0)
21. {x1= -b/(2*a);
22. printf("Quadratic equation has unique root x = %f", x1);
23. }
24. else
25. {x1=(-b + sqrt(delta))/(2*a);
26. x2=(-b - sqrt(delta))/(2*a);
27. printf("Quadratic equation has 2 roots\n x1=%f \n x2=%f",x1,x2 );
28. }
29. } 12
30. }
User screen

13
The switch statement

switch (expression)
{
case value1: statements_1
case value2: statements_2
/* more cases */
[default: default_statements]
}

14
The switch statement
Compute value of
expression

F F
exp=Value 1 exp=Value 2  default ? F

T T T
Statements1 Statements2 Statementsn+1

 break ? F  break ? F  break ? F


T T T
Next statement

• break statement are used to end processing of a particular labeled statement


within the switch statement.
• Without break, the program continues to the next labeled statement,
executing the statements until a break or the end of the statement is reached.

15
Example 1

Write a program that asks the user to type a number


between 1 and 7 and print the day of week corresponding
to that number (1 for Sunday… 7 for Saturday)

16
Program and user screen
1. #include <stdio.h>

2. main(){

3. int a;

4. printf("\nEnter a number value for a weekday (from 1 to 7): "); scanf("%d",&a);

5. switch(a) {

6. case 1: printf("Sunday"); break;

7. case 2: printf("Monday"); break;

8. case 3: printf("Tuesday"); break;

9. case 4: printf("Wednesday"); break;

10. case 5: printf("Thursday"); break;

11. case 6: printf("Friday"); break;

12. case 7: printf("Saturday"); break;

13. default: printf("Error");

14. }

15. }

17
Homework

• Return the number of days in the month of the


Gregorian calendar.
• The program ask the user to type the number of a month
and a year

18
4.3.Repetition

• while statement
• do…. while statement
• for statement
• Loop interruption: break and continue

19
while statement

while (expression) statement

20
Find the largest integer that satisfies 3n5-317n <
5
1. #include <stdio.h>
2. #include <math.h>
3. main()
n = 10
4. { while (3*pow(n,5)-317*n >= 5)
5. int n=0; n--;
6. while (3* pow(n,5) - 317*n < 5) n++;

7. printf("%4d",n-1);
8. }
n= 3

21
Find the output of the program

1. #include <stdio.h>
2. main()
3. {
4. int i=3;
5. while (i > 1){
6. if(i % 2==0) i = i / 2;
7. else i = i * 3 + 1;
8. printf("%4d",i);
9. }
10.}

10 5 16 8 4 2 1
22
do … while statement

do statement while (expression)

23
Example 1

• Enter a mark, if it is not between 0 and 10, notify the


user to re-enter.
• Implementation:
– The if statement
 Only check once
– The for statement
The number of iteration is unknown.
 Use a loop without pre-determining the number
of iterations: while / do while

24
Use do…while loop

1. main(){
2. float mark;
3. do
4. {printf("Input a mark between 0 and 10:");
5. scanf("%f",&mark);
6. if (mark < 0 || mark > 10)
7. printf("\nThe entered mark is invalid
!\n");
8. }
9. while (mark < 0 || mark > 10);
10. printf("\nThe entered mark is: %.2f",mark);
11.}

25
Use do while loop

26
Use while loop

1. #include <stdio.h>
2. main(){
3. float mark;
4. printf("Input a mark between 0 and 10:");
scanf("%f",&mark);
5. while (mark < 0 || mark > 10) {
6. printf("\nThe entered mark is invalid
!\n");
7. printf("Enter the mark
again(0<=mark<=10):");
8. scanf("%f",&mark);
9. }
10. printf("\nThe entered mark is: %.2f",mark);
11.} 27
Use while loop  Result

28
for statement

for (expression1; expression2; expression3)


statement

29
Use cases of for loop

int i;
for(i = 0; i < 100; i++) statement;

int i;
for(i = 0; i < 100; i+=2) statement;

int i;
for(i = 100; i > 0; i--) statement;

for(int i = 0; i < 100; i++) statement;


for(int i = 100; i > 0; i--) statement;

30
Example 1: Print odd numbers less than 100

1. #include <stdio.h>
2. main(){
3. int i;
4. for(i = 1;i<100;i++) {
5. if(i%2 == 1) printf("%5d",i);
6. if((i+1)%20 ==0) printf("\n");
7. }
8. }

31
Example 2: Print odd numbers less than 100 in descending order

1. #include <stdio.h>
2. main(){
3. int i;
4. for(i = 99;i > 0;i-=2) {
5. printf("%5d",i);
6. if( (i-1) % 20 == 0) printf("\n");
7. }
8. }

32
Example 3: Input number n and print its factorial

1. main()
2. { long P = 1;
3. int n, i;
4. printf("Input n : ");scanf("%d",&n);
5. for(i = 1;i<=n;i++)
6. P = P * i;
7. printf("%d!= %ld",n,P);
8. }

33
Example 4: Compute sum of harmonic series
• The harmonic series is: 1 +1/2+…+1/n. n is entered from
keyboard
1. #include <stdio.h>
2. main()
3. {
4. float S = 0.0;
5. int n, i;
6. printf("Input n : ");scanf("%d",&n);
7. for(i = 1;i <= n;i++)
8. S = S + (float)1/i; //S+=1.0/i;
9. printf("Sum of harmonic series: %7.4f ",S);
10.}

34
Example 5: Find Amstrong numbers of 3 digits

An Amstrong number of 3 digit is an integer that the sum of


the cubes of its digits is equal to the number itself.
1. #include <stdio.h>
2. main()
3. {int i, a, b, c;
4. for(i = 100;i<1000;i++){
153
5. a = i / 100;
6. b = i % 100 / 10;
370
7. c = i % 100 % 10; 371
8. if(a*a*a+b*b*b+c*c*c == i) 407
9. printf("%d\n",i);
}
}
35
Various forms of for loop
• Initialization part can be skipped
char c; int i=0; Hello world
for( ; (c=getchar())! = '\n’ ; i++) Hello world
Number of characters: 11
putchar(c);
printf(“\nNumber of characters:
%d”,i);
• Condition can be skipped, comma operator
can be used Hello world
for(i=0 ; ; c=getchar(), i++)
if(c==‘\n’) break; Number of characters: 12
printf(“\ nNumber of characters:
%d”,i);
• The body of the loop may be empty
Hello world
for(i=0 ; getchar() != ‘\n’, i++);
Number of characters : 11
printf(“\nNumber of characters:
%d”,i);

36
Loop Interruption: break and continue

• break
The break statement skips any statements between the break
and the bottom of the loop; the break statement ends the loop
and control resumes with the first statement following the
loop.

• continue
The continue statements skips any statements between the
continue and the bottom of the loop; the next iteration of the
loop begins (including the update statement in the case of a for
loop).

37
Continue vs break

38
Example 1

• Compute sum of the first 100 integers except those


divisible by 5
1. #include <stdio.h>
2. main()
3. {
4. int i;
5. int sum = 0;
6. for(i = 1;i<=100;i++)
7. {
8. if(i % 5 == 0) for(i=1;i<=100;i++)
9. continue;
if (i % 5 != 0)
10. sum += i;
11. } sum += i;
12.}
39
Example 2
#include <stdio.h>
main()
{ int i,j;
for(i = 0;i<10;i++) {
for (j=0; j < 10; j ++) {
if(j > i){
break;
}//if
}//for _ j
printf("i:%d j:%d\n",i,j);
}//for_i
}

40
Example 3

#include <stdio.h>
main()
{
int i;
for(i = 1;i<=10;i++)
{
if(i == 5) continue;
printf(“%5d”,i);
if(i==7) break;
}
}

41
Example 4
#include <stdio.h>
main()

{ int i,j;
for(i = 0;i<10;i++) {
for (j=0; j < 10; j ++) {
if(j > i){
break;
}//if
}//for _ j
printf("i:%d j:%d\n",i,j);
}//for_i
}

42

You might also like