You are on page 1of 38

Unit 4

The control flow


C control structures
• Selection
if
if . . . else
switch

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

2
If statement

Form1 Form2 (if … else)


If (expression) statement1
If (expression)
else statement2
statement

3
Expression
Any expression is valid. But logical expessions are
more popular
Logical expressions may include:

6 Relational Operators
< <= > >= == !=

3 Logical Operators
! && ||
4
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.

5
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!");
16.}

6
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

7
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?


8
1. #include <stdio.h>

Program
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. }
30. }

9
User screen

10
The switch statement

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

11
The switch 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.
12
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)

13
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. }

14
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

15
The while statement

while (expression) statement

16
Find the largest integer that satisfies
5
3n -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 17
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
18
The do while statement
do statement while (expression)

19
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

20
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.}
21
Use do while loop

22
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.}

23
Use while loop  Result

24
The for statement

for (expression1; expression2; expression3) statement

25
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;
26
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. }

27
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. }

28
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. }

29
Example 4: Calculate sum of
harmonic series 1 +1/2+…+1/n
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.}

30
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);
}
}
31
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);

32
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).

33
Continue vs break

34
Calculate 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)
9. continue; for(i=1;i<=100;i++)
10. sum += i; if (i % 5 != 0)
11. } sum += i;
12.}
35
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
}

36
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;
}
}

37
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
}

38

You might also like