C Programming Topic 1: Control Structures
C Programming Topic 1: Control Structures
C Programming Topic 1: Control Structures
true
num1 >= num2 diff = num1 – num2
false
if-else
true
num1 >= num2 diff = num1 – num2
?
false
diff = num2 – num1
...
if (num1 >= num2)
diff = num1 – num2;
else
diff = num2 – num1;
...
if-else
if ( grade >= 90 ) // 90 and above
printf("A“);
else if ( grade >= 80 ) // 80-89
printf("B“);
else if ( grade >= 70 ) // 70-79
printf("C“);
else if ( grade >= 60 ) // 60-69
printf("D“);
else // less than 60
printf("F“);
if example
#include <stdio.h>
int main ( )
{
int num1, num2, num3, min = 0;
return 0;
}
Compound statement
int main()
{
int value;
scanf(“%d”,&value);
switch (value) {
case 1 :
printf(“1 received\n”);
break;
case 2 :
printf(“2 received\n”);
break;
default :
printf(“ values except 1 and 2 were received.\n”);
break;
}
return 0;
}
while
num = 1;
Sum = 0;
true
sum = sum + num;
num <= 10
num = num + 1;
false num = 1;
sum = 0;
while (num <= 10) {
sum = sum + num;
num = num + 1;
}
do-while
The body (block) of do-while
num = 1;
Sum = 0; statement is executed at least
once.
int main ()
{
int total = 0, score, count = 0;
float average;
while (score != 0) {
total += score;
count++;
scanf("%d",&score);
}
if (count == 0)
printf (“No input received!");
else {
average = (float) total / count;
printf (“total: %d \n", total);
printf (“average: %5.2f \n", average);
}
return 0;
}
for
for ( (1); (2); (3) ) (1)
{ // for-repetition body
....
. . . . // {} is not necessary
// if there is only one statement in body FALSE
} (2)
TRUE
Repetition
(1) control variable initialization
(2) Test Conditon
(3) Modification of control variable value
body
* (3)
Example
for example
#include <stdio.h>
int main ()
{
int total = 0, score, count;
float average;
if (count == 0)
printf (“No input received!");
else {
average = (float) total / count;
printf (“total: %d \n", total);
printf (“avarage: %5.2f \n", average);
}
return 0;
}
break
break in loop
Go out of the loop block and execute next to the
loop
example
while (1) {
scanf("%d",&j)
if (j == 0)
break;
result = i/j;
}
continue
continue in loop
Go to condition test of the loop
Example
return 0;
}
In fin ite Lo o p
If the condition of the loop is always TRUE,
the body of the loop is executed infinitely
example
while(1) {
i=0;
i++; int count = 1;
printf(“%d”,i); while (count != 100)
} count += 2;