Eee0115 2
Eee0115 2
Chapter 3: Structured
Program Development in C
C How to Program
1 Deitel & Deitel
2
Algorithms
Pseudocode
Control Structures
The if Selection Statement
The if...else Selection Statement
The while Repetition Statement
3
Algorithms
Algorithm is defined as the actions to be
executed in a specific order to solve a
given problem.
Program control is an important concept
and it defiens the specific order in which
statements are to be executed.
4
Pseudocode
Artificial or informal language which is
used to develop algorithms
Pseudocodes are not executed on
computers.
They are similar to everyday English.
Pseudocodes can be converted easily to C
program.
5
Control Structures
All programs can be written in terms of 3
control structures:
Sequence structures: Statements executed
sequentially. It is default control structure.
Selection structures: if, if-else, switch.
Repetition structures: while, do-while, for.
6
If (grade<50)
printf(“Failed\n”);
else
printf(“Passed\n”);
Ternary conditional operator (?:)
It has three arguments (condition, value
if true, value if false)
printf( "%s\n", grade >= 60 ?
"Passed" : "Failed" );
grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );
10
if(a>10)
{
printf("Your value is greater than 10\n");
printf("Enter a new value\n");
}
12
Counter-Controlled Repetition
1 /* Fig. 3.6: fig03_06.c
2 Class average program with counter-controlled repetition */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grade to be entered next */
9 int grade; /* grade value */
10 int total; /* sum of grades input by user */
11 int average; /* average of grades */
12
13 /* initialization phase */
14 total = 0; /* initialize total */
15 counter = 1; /* initialize loop counter */
16
17 /* processing phase */
18 while ( counter <= 10 ) { /* loop 10 times */
19 printf( "Enter grade: " ); /* prompt for input */
20 scanf( "%d", &grade ); /* read grade from user */
21 total = total + grade; /* add grade to total */
22 counter = counter + 1; /* increment counter */
23 } /* end while */
14
Counter-Controlled Repetition
24
25 /* termination phase */
26 average = total / 10; /* integer division */
27
28 printf( "Class average is %d\n", average ); /* display result */
29
30 return 0; /* indicate program ended successfully */
31
32 } /* end function main */
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
15
Assignment Operators
Assignment operators can be used
instead of assignment expressions:
a=a+5 can be written as a+=5
a=a-5 can be written as a-=5
a=a*5 can be written as a/=5
a=a/5 can be written as a+=5
a=a%5 can be written as a%=5
23
5
6
6