ECET 264 C Programming Language with
Applications
Lecture 7
C Program Control
Paul I. Lin
Professor of Electrical & Computer Engineering
Technology
http://www.etcs.ipfw.edu/~lin
Lecture 7 - Paul I. Lin
1
Lecture 7
C Program Controls
Common Programming Errors:
Syntax Errors, Logic Errors, Run-time Errors,
and Undetected Errors
C Program Control Structures
• Repetition Statements
For Statement
Do … While Repetition Statement
• Selection Statements
Switch … multiple selection statement
Break
Continue
Lecture 7 - Paul I. Lin
2
1
Lecture 7
C Program Controls
C Programming Examples
• Example 7-1: Interest Calculation
• Example 7-2: ASCII Number Generation
• Example 7-3: Read Keyboard Inputs and Echo
them on to the Monitor Screen
• Example 7-4: Generating 10 Random Numbers
• Example 7-5: Generating Seeded and
Unseeded Random Numbers
• Example 7-6: Counting the Number of a, b, and
c characters in a text file
• Example 7-7: A Calculator Program
Lecture 7 - Paul I. Lin
3
Common Programming Errors
Syntax errors
• Grammatical errors, such as misspelling or incorrect
punctuation
• Can be caught by the compiler
Logic errors (Caused as a result of faulty program design)
• Program logical errors
• Misuse operators, such as ==, =
• Program does not terminate properly or an endless loop
• Errors caused by inappropriate end of data
Run-time errors (Errors occur during the execution of a
program)
Other undetected errors (Fail to perform its intended task;
incorrect results)
Lecture 7 - Paul I. Lin
4
2
Repetition Essentials
Repetition is a group of statements the computer
executes repeatedly while the condition remains
true
Counter Controlled repetition (definite repetition)
• A control variable (or loop counter)
• A proper initial value for the control variable
• The increment (or decrement) by which the
control variable is modified each time through
the loop
• Testing final value of the control variable to
know when to end the loop
5
Lecture 7 - Paul I. Lin
Repetition Essentials
(cont.)
Sentinel Controlled repetition (indefinite
repetition)
• The precise number of repetitions is not
known in advance
• The loop includes statement(s) that obtain
ending condition data each time the loop
is performed
• The ending condition is determined
through a distinct input data called
sentinel value which indicates “end of
data”
Lecture 7 - Paul I. Lin
6
3
Repetition Structures
A loop is a form of repetition in which a
sequence of statements is repeated a
number of times.
Repetition structures: are to take actions
until the condition fails.
• while
• for
• do … while
7
Lecture 7 - Paul I. Lin
Repetition Structures
(cont.)
while Loop
Control variables used in the loop
control testing must be initialized
Testing for the termination condition is
done at the top of the while() loop
while (1) … endless loop which is
equivalent to
#define true 1
while(true){ ….}
or
for ( ; ; ) { ….}
Lecture 7 - Paul I. Lin
8
4
for Loop
for statement
• is a repetition statement
• provides a leading-test construct with
initialization and re-initialization provisions
• for loop allows to repeat the statements for a
fixed number of times
• Basic Format:
for(initialization; end_cond_checking; update)
{ s1;
s2;
…
sn; }
9
Lecture 7 - Paul I. Lin
for Loop
(cont.)
Form 1: Null Statement (can be used as a
short time delay routine)
for (i = 0; i< 10; i++) ;
NO statement to be executed
Form 2: Simple Statement
Loop continuation condition
for (i = 0; i < 10; i++) 10 is a final value of control
sum += 1; variable
i =0
ONE statement to be executed
True
i< 10
?
False
sum += 1
i ++
Lecture 7 - Paul I. Lin
10
5
for Loop
(cont.)
Form 3: Compound Statement
for (init; end_cond_checking; update)
{ s1; s2; … }
More than ONE statement
to be executed
Form 4: Nested for Loops
for ( ; ;) /* End Less Loop */
{ for (init; end_cond_checkig; update)
{ s1; s2; s3;
for (init; end_cond_checking; update)
s4;
} Include more then one FOR
statement to be executed
}
Lecture 7 - Paul I. Lin
11
Example 7 – 1
Interest Calculation
This C program computes compound interest using the
FOR loop.
A person invests $500.00 in a saving account yielding
3% of interest. Assuming that all interest is left on
deposit in the account, calculate and print the amount of
money in the account at the end of each year for 10
years using the following equation:
a = p(1+r)n
where p is the original amount invested
r is the annual interest rate
n is the number of year
a is the amount on deposit at the end of the nth year
Lecture 7 - Paul I. Lin
12
6
Example 7 – 1 (cont.)
Interest Calculation
/* Calculating compound interest*/
#include <stdio.h>
#include <math.h>
/* function main begins program execution */
int main()
{
double amount;
/* amount on deposit */
double principal = 500.0; /* starting principal */
double rate = 0.03; /* annual interest rate */
int year;
/* year counter */
/* output table column head */
printf( "%4s%21s\n", "Year", "Amount on deposit" );
Lecture 7 - Paul I. Lin
13
Example 7 – 1 (cont.)
Interest Calculation
/* calculate amount on deposit for each of ten years */
for ( year = 1; year <= 10; year++ )
{
/* calculate new amount for specified year */
amount = principal * pow( 1.0 + rate, year );
/* output one table row */
printf( "%4d%21.2f\n", year, amount );
} /* end for */
return 0; /* indicate program ended successfully */
}
Lecture 7 - Paul I. Lin
14
7
Example 7 – 1 (cont.)
Interest Calculation
Lecture 7 - Paul I. Lin
15
Example 7 – 2
ASCII Number Generation
Write a C program to generate ASCII numbers (0 to 9)
and display them as both decimal and hex number
on the screen:
%c -- the format specified reserves a default length
of spaces for printing a character
%d -- the format specified reserves a default length
of spaces for printing a decimal number
%x -- the format specified reserves a default length
of spaces for printing a hex number
Lecture 7 - Paul I. Lin
16
8
Example 7 – 2 (cont.)
ASCII Number Generation
#include <stdio.h>
void main()
{
char ascii;
for (ascii = '0'; ascii <= '9'; ascii++)
{
printf("ASCII %c = Decimal %d = Hex %x \n", ascii,
ascii, ascii);
}
}
Lecture 7 - Paul I. Lin
17
Example 7 – 2 (cont.)
ASCII Number Generation
Output:
ASCII 0 = Decimal 48 = Hex 30
ASCII 1 = Decimal 49 = Hex 31
ASCII 2 = Decimal 50 = Hex 32
ASCII 3 = Decimal 51 = Hex 33
ASCII 4 = Decimal 52 = Hex 34
ASCII 5 = Decimal 53 = Hex 35
ASCII 6 = Decimal 54 = Hex 36
ASCII 7 = Decimal 55 = Hex 37
ASCII 8 = Decimal 56 = Hex 38
ASCII 9 = Decimal 57 = Hex 39
Lecture 7 - Paul I. Lin
18
9
Example 7 – 3: Read Keyboard Input
and Echo them on to Monitor Screen
/* char0.c A simple for loop for
controlling the activities of the
keyboard input and screen
output. */
#include <stdio.h>
#define NEWLINE '\n'
void main()
{
char name[30];
int c;
/*Execute following forever, CTRL
C to stop*/
for(;;)
{
printf("\nPlease enter your
name: ");
gets(name);
puts("Is this your name?");
puts(name);
printf("\nPlease enter a digit:
");
c = getchar();
puts("\nIs this the digit?");
putchar(c);
putchar(NEWLINE);
fflush(stdin);
/* Flush the keyboard buffer */
}
} /* end of char0.c */
Lecture 7 - Paul I. Lin
19
Example 7 – 3: Read Keyboard Input and
Echo them on Monitor Screen (cont.)
Output:
Please enter your name: Paul Lin
Is this your name?
Paul Lin
You entered
Please enter a digit:2
Is this the digit?
2
Please enter your name:
Lecture 7 - Paul I. Lin
20
10
Example 7 – 4
Generating 10 Random Numbers
/* This program seeds the random-number generator
with the time, then displays 10 random integers */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main( void ){
int i;
/* Seed the random-number generator with current time
so that the numbers will be different every time we
run the program. */
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i < 10; i++ )
printf( " %6d\n", rand() );
}
Lecture 7 - Paul I. Lin
21
Example 7 – 4 (cont.)
Generating 10 Random Numbers
Sample Output:
19430
28222
9710
12070
7513
9501
1767
26041
11872
4097
Lecture 7 - Paul I. Lin
22
11
Example 7 – 5: Generating Seeded and
Unseeded Random Numbers
/* randgen.c - Generating seeded and unseeded pseudo
random numbers */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main(void)
{
int n;
/* Generate 4 unseeded pseudo random numbers*/
for(n = 1; n < 5; n++)
printf("%d\t", rand());
puts("\n");
/* Generate time() function seeded peudo random
numbers */
srand((unsigned)time(NULL));
Lecture 7 - Paul I. Lin
23
Example 7 – 5: Generating Seeded and
Unseeded Random Numbers (cont.)
for(n = 1; n < 5; n++)
printf("%d\t", rand());
puts("\n");
/* Reset peudo random generator */
srand(1);
for(n = 1; n < 5; n++)
printf("%d\t", rand());
puts("\n");
}
Lecture 7 - Paul I. Lin
24
12
Example 7 – 5: Generating Seeded and
Unseeded Random Numbers (cont.)
25
Lecture 7 - Paul I. Lin
Example 7 – 6: Counting the Number of
a, b, and c Characters
/* if0.c - Counting A, B, C characters */
#include <stdio.h>
#define SIZE 81
#define FORMAT "A = %d, B = %d, C = %d\n"
void main()
{
int i;
int a, b, c; // counters
char ch, s[SIZE];
a = b = c = 0;
Lecture 7 - Paul I. Lin
26
13
Example 7 – 6: Counting the Number of
a, b, and c Characters (cont.)
for(;;)
// Run forever; Enter <Ctrl C> to exit
{
puts("Enter a string");
gets(s);
for(i = 0; (ch = s[i]) != '\0'; i++)
{
if((ch == 'A') || (ch == 'a')) a++;
if((ch == 'B') || (ch == 'b')) b++;
if((ch == 'C') || (ch == 'c')) c++;
}
printf(FORMAT, a, b, c);
}
}
27
Lecture 7 - Paul I. Lin
Example 7 – 6: Counting the Number of
a, b, and c Characters (cont.)
Output:
You entered
Enter a string
The C Programming Language
A = 3, B = 0, C = 1
Enter a string
Lecture 7 - Paul I. Lin
28
14
do … while
while loop tests for the termination
condition at the top of the while() loop
before the body of the loop performed
do … while loop always executes its
loop body at least once before testing
the termination conditions
do … while loop is good to perform
counting, adding, searching, sorting,
monitoring, etc
29
Lecture 7 - Paul I. Lin
do … while
(cont.)
Syntax:
Form 1: Simple Statement
do {
statement;
}while (condition);
Form 2: Compound Statements
do{
s1; s2; s3;
……
} while (condition);
Lecture 7 - Paul I. Lin
30
15
do … while
(cont.)
Using Relational and Logical operators for
Checking Ending Condition:
do { ..} while(1)
/* Endless loop */
do { ..} while(a > b) /* a greater than b */
do { ..} while(a <= b) /* a less or greater than b */
do { ..} while(a != b) /* a not eaual to b */
do { ..} while(a == b) /* a equal to b */
do { ..} while(a < (c + b)) /* a less than c + b */
do { ..} while(!a)
/* while not a */
do { ..} while(a && b) /* while a and b are both
nonzero or true */
do { ..} while(a || b)
/* while either a or b is
nonzero or true */
Lecture 7 - Paul I. Lin
31
switch
A multiple selection statement
Consists of a series of case labels, and
optional default case
Multi-way branch (a chain of if-else
statement)
To select among several different cases
break is used to end each case to exit the
switch
The default case is optional
Lecture 7 - Paul I. Lin
32
16
switch (cont.)
General form of switch(n)
Syntax: switch (n)
{
case 1: statement 1;
break;
……
case n: statement n;
break;
default: statement;
}
where n … can only be an integer, unsigned
integer, or character type variable
Lecture 7 - Paul I. Lin
33
switch (cont.)
Example:
int j = 3;
switch(j)
{
case 1:
printf(“case 1 \n”);
break;
case 2: printf(“case2 \n”);
break;
default: printf(“case others \n”);
break;
}
Lecture 7 - Paul I. Lin
34
17
Example 7 – 7
A Calculator Program
Problem Statement
You are asked to write a C program that can be used as
a calculator program. The requirement of this
program is as follows:
• It will run under a DOS virtual machine using text
based user interface.
• It will prompt the user to enter two numbers
• It then asks for one of the calculation: addition,
subtraction, multiplication, or division
• The program calculates the result
• Displays answer and repeats the same calculation
Analysis
• Three variables are required
• switch, case, multi-decision making is preferred
• Endless loop, Ctrl C to exit the loop
Lecture 7 - Paul I. Lin
35
Example 7 – 7
A Calculator Program (cont.)
/* switch0.c */
#include <stdio.h>
#include <stdlib.h>
void main() {
float n1, n2, result;
char op[2];
while(1) /* Enter <Ctrl C> to exit */
{
fflush(stdin);
puts("Hit any key to continue, Ctrl C to exit\n");
getchar(); /* waiting for user to input */
printf("\nEnter a number: ");
scanf(“%f”, &n1); /* Console input */
printf("\nEnter second number: ");
scanf(“%f”, &n2); /* Console input */
Lecture 7 - Paul I. Lin
36
18
Example 7 – 7
A Calculator Program (cont.)
printf("\nSelect an operator +,-,*, x, / or \\: ");
scanf(“%s”, op);
switch(op[0])
{
case '+': result = n1 + n2;
printf("%f\n", result); break;
case '-': result = n1 - n2;
printf("%f\n", result); break;
case '*': case 'x':
case 'X': result = n1 * n2;
printf("%f\n", result); break;
case '/':
case '\\': result = n1 / n2;
printf("%f\n", result); break;
default: puts("Wrong operator entered");
Lecture 7 - Paul I. Lin
} } }
37
Example 7 – 7
A Calculator Program (cont.)
Output:
Hit any key to continue
Enter a number: 12.0
Enter second number: 20.0
Select an operator +,-,*, x, / or \: *
240.000000
Hit any key to continue
Lecture 7 - Paul I. Lin
38
19
Summary
Common Program Errors
C Program Control
• More Repetition Statements
For Statement
Do … While Repetition Statement
• More Selection Statements
Switch multiple selection statement
Next • Break and Continue statement
• Equality operator (==) and assignment
operator (=)
Lecture 7 - Paul I. Lin
39
Question?
Answers
[email protected]
Lecture 7 - Paul I. Lin
40
20
© Copyright 2026 Paperzz