Transcript if/else

Control Structures and Data Files
1
Structured Programming
Use simple control structures to organize the
solution to a problem

Sequence
no


yes
Selection
Repetition
no
yes
2
Sequence
3
Selection
4
Repetition
5
Extras

Evaluation of alternative solution



Error condition



A problem can be solved in many different ways
Which is the best (e.g, faster, memory req)
Do not trust user! Check the data. A=b/c;
Be clear about specifications
Generation of Test Data



Test each of the error conditions
Program validation and Verification
Program walkthrough
6
Conditional Expressions


Selection and repetition structures use
conditions, so we will first discuss them
A condition is an expression that can be
evaluated to be



TRUE (any value > 0) or
FALSE (value of 0)
Conditional Expression is composed of
expressions combined with relational
and/or logical operators
7
Relational Operators






==
!=
<
>
<=
>=
equality
non equality
less than
greater than
less than equal to
greater than equal to
(x == 3)
(y != 0)
(x<y)
(y>10)
(x<=0)
(x>=y)
!!! a==b vs. a=b !!!
8
Examples






a<b
x+y >= k/m
fabs(denum) < 0.0001
d= b > c
if (d)
a=b+c;
a < b < c ???
9
Logical Operators



!
&&
||
not
and
or
!(x==0)
(x>=0) && (x<=10)
(x>0) || (x<0)
A
B
A && B A || B
!A
!B
False
False
False
False
True
True
False
True
False
True
True
False
True
False
False
True
False
True
True
True
True
True
False
False
10
Examples



a<b<c is not the same as (a<b) &&
(b<c)
a<b && c>=5
a+b * 2 < 5 && 4>=a/2 || t-2 < 10
a=3, b=5, t=4
11
Precedence for Arithmetic,
Relational, and Logical Operators
12
Exercise

Assume that following variables are declared
a = 5.5

b = 1.5
k = -3
Are the following true or false
a < 10.0 + k
a + b >= 6.5
k != a-b
!(a == 3*b)
a<10 && a>5
fabs(k)>3 || k<b-a
13
Selection Statements
14
Selection Statements



if
if else
switch
15
If statement


if(Boolean expression)
statement; //single statement
if(Boolean expression)
{ //more than one statement
statement1;
.
statement n;
}
16
Examples
• if (x>0)
k++;
•if (x>0)
{
x=sqrt(x);
k++;
}
4
x
2
-2
x
2
4
x
2
-2
x
2
k
k
k
k
17
if - else statement


if (boolean expression)
statement1;
else
statement2;
if (boolean expression)
{
statement block1
}
else
{
statement block2
}
x=y;
x=y;
k=3;
18
If-else statement

What does the following program do? Assume
that x, y, temp are declared.
if (x>y)
temp = x;
else
temp = y;
1
x
3
y
?
temp
3
x
1
y
?
temp
19
If-else statement
Split the following statement into two separate if
statements
if (x>y)
temp = x;
else
temp = y;
if (x>y)
temp = x;
if (x<=y)
temp = y;
20
Exercise

Write an if-else statement to find both the maximum and minimum
of two numbers. Assume that x,y, min, max are declared.
if (x>y)
{
max = x;
min = y;
}
else
{
max = y;
min = x;
}
Ex:
x = 10, y = 5
y = 3, y = 4
x = 6, y = 6
21
nested if-else
if(x > y)
if(y < z)
k++;
else
m++;
else
j++;
if (y<z)
k++;
else
m++;
22
Exercise
int x=9, y=7, z=2, k=0, m=0, j=0;
if (x > y)
9
if(y < z)
x
k++;
else
2
z
m++;
else
0
j++;
m
7
y
0
k
0
j
What are the values of j, k and m
after execution of if statement?
23
Exercise
int x=3, y=7, z=2, k=0, m=0, j=0;
if (x > y)
3
if(y < z)
x
k++;
else
2
z
m++;
else
0
j++;
m
7
y
0
k
0
j
What are the values of j, k and m
after execution of if statement?
24
Exercise

What is the output of the following program
int a = 5, b = 3;
if (a>10)
a = 50;
b = 20;
printf(" a = %d, b = %d\n",a, b);
if (a>10) {
a = 50;
b = 20;
}
printf(" a = %d, b = %d\n",a, b);
if (a>10)
a = 50;
b = 20;
printf(" a = %d, b = %d\n",a, b);
if (a>10) {
a = 50;
b = 20;
}
printf(" a = %d, b = %d\n",a, b);
25
Exercise

Given a score and the following grading scale write a
program to find the corresponding grade.
80-100
60-79
40-59
0-39
A
B
C
D
26
Solution
if ((score >= 80) && (score <=100))
grade = 'A';
else if ((score >= 60) && (score <= 79))
grade = 'B';
else if ((score >= 40) && (score <= 59))
grade = 'C';
else if ((score >= 0) && (score <= 39))
grade = 'D';
else
printf("Invalide Score\n");
27
Alternate Solution
if (score > 100)
printf(“Invalid Score\n”);
else if (score >= 80)
grade = 'A';
else if (score >= 60)
grade = 'B';
else if (score >= 40)
grade = 'C';
else if (score >= 0)
grade = 'D';
else
printf("Invalide Score\n");
28
Exercise

What is the value of a at the end of the following ifelse statement (chapter3e2.c)
int a = 750;
if (a>0)
if (a >= 1000)
a = 0;
else
if (a <500)
a *= 2;
else
a *= 10;
else
a += 3;
if (a>=1000)
a = 0;
else
if (a<500)
a *= 2;
else
a *= 10;
if (a<500)
a *= 2;
else
a *= 10;
29
Exercise


Write a program that reads 3 numbers a, b and c
from user and computes minimum, maximum and
median of the numbers.
Example:

a = 2, b = 5, c = 3


minimum = 2, maximum = 5, median = 3
a = 2, b = 2, c = 3

minimum = 2, maximum = 3, median = 2
30
Minimum
if ((a<b) && (a<c))
min = a;
else if ((b<a) && (b<c))
min = b;
else if ((c<a) && (c<b))
min = c;
31
Maximum
if ((a>b) && (a>c))
max = a;
else if ((b>a) && (b>c))
max = b;
else if ((c>a) && (c>b))
max = c;
32
Median
if ((a<b) && (b<c))
median = b;
else if ((c<b) && (b<a))
median = b;
else if ((b<a) && (a<c))
median = a;
else if ((c<a) && (a<b))
median = a;
else if ((b<c) && (c<a))
median = c;
else if ((a<c) && (c<b))
median = c;
33
Alternate Solution for Median
if (((a<b) && (b<c)) || ((c<b) && (b<a)))
median = b;
else if (((b<a) && (a<c)) || ((c<a) && (a<b)))
median = a;
else if (((b<c) && (c<a)) || ((a<c) && (c<b)))
median = c;
34
Exercise continued
Find minimum of 3 numbers

1.
Write an if statement to check if minimum is a
if (condition)
min = a;
2.
3.
4.


what should
be condition?
Write an if statement to check if minimum is b
Write an if statement to check if minimum is c
Combine 1-3 into a single nested if-else statement
Similarly find maximum of 3 numbers
Find median of 3 numbers
35
Exercise

Write a program that reads a point (x, y) from
user and prints the region it resides in.
For example
Region 2
Region 1
Enter x, y:
3 -1
Point in Region 4
Region 3
Region 4
Enter x, y: -1 -5
Point in Region 3
36
Solution
if ((x>0) && (y>0))
printf("Region 1\n");
else if ((x<0) && (y>0))
printf("Region 2\n");
else if ((x<0) && (y<0))
printf("Region 3\n");
else if ((x>0) && (y<0))
printf("Region 4\n");
37
Alternate Solution
if (x>0)
if (y>0)
printf("Region1\n");
else
printf("Region4\n");
else
if (y>0)
printf("Region2\n");
else
printf("Region3\n");
38
Switch Statement
switch(expression)
{
case constant:
statement(s);
break;
case constant:
statement(s);
break;
}
/* default is optional*/
default:
statement(s);
39
Switch Statement



Expression must be of type integer or character
The keyword case must be followed by a constant
break statement is required unless you want all subsequent statements
to be executed.
switch (op_code)
{
case ‘N’:
printf(“Normal\n”);
break;
case ‘M’:
printf(“Maintenance Needed\n”);
break’
default:
printf(“Error\n”);
break;
}
40
Exercise

Convert the switch statement into if statement.
switch (op_code)
{
case ‘N’:
printf(“Normal\n”);
break;
case ‘M’:
printf(“Maintenance Needed\n”);
break;
default:
printf(“Error\n”);
break;
}
if (op_code == ‘N’)
printf(“Normal\n”);
else if (op_code == ‘M’)
printf(“Maintenance Needed\n”);
else
printf(“Error\n”);
41
Exercise
Convert the following nested if/else statements
to a switch statement
if (rank==1 || rank==2)
printf("Lower division \n");
else
{
if (rank==3 || rank==4)
printf("Upper division \n");
else
{
if (rank==5)
printf("Graduate student \n");
else
printf("Invalid rank \n");
}
}
42
Solution
switch(rank)
{
case 1:
case 2:
printf("Lower Division\n");
break;
case 3:
case 4:
printf("Upper Division\n");
break;
case 5:
printf("Graduate Student\n");
break;
default:
printf("Invalid Rank");
break;
}
43
Exercise

Write a switch statement that prints the number of days
in the month given an integer corresponding to month






int month;
switch (month)
1-12 represents months January – December.
February has 28 days.
April, June, September, November has 30 days
January, March, May, July, August, October, December has 31
days.
44
Solution
switch(month)
{
case 2:
printf("28 Days\n");
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
printf("31 days\n");
break;
case 4: case 6: case 9: case 11:
printf("30 days\n");
break;
default:
printf("Invalid month");
break;
}
45
Loop (Repetition) Structures
46
Loop (repetition) statements



while statement
do while statement
for statement
47
while statement


while(expression)
statement;
while(expression)
{
statement;
statement;
.
}
x=1;
while (x<5)
x = x + 1;
x = 1;
while (x<5)
{
x = x+1;
printf(“X=“%d”,x);
}
48
Example: lecture2e4.c
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0;
double radians;
printf("Degrees to Radians \n");
while (degrees <= 360)
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
degrees += 10;
}
return 0;
}
49
do while

do

do
{
statement;
while(expression);
statement1;
statement2;
.
} while(expression);

x=1;
do
x = x + 1;
while (x<5);
x = 1;
do
{
x = x+1;
printf(“X=“%d”,x);
} while (x<5);
note - the expression is tested after the statement(s)
are executed, so statements are executed at least
once.
50
Example: lecture2e5.c
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0;
double radians;
printf("Degrees to Radians \n");
do
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
degrees += 10;
} while (degrees <= 360);
return 0;
}
51
for statement

for(initialization; test; increment/decrement)
statement;
for (x=1; x<5; x++)
printf(“x=%d\n”,x);

for(initialization; test; increment/decrement)
{
statement;
for (x=1; x<5; x++)
{
statement;
printf(“X=“%d\n”,x);
.
printf(“X^2 = %d\n”,x*x);
}
}
52
for statement
initalize
test
increment/
decrement
true
statement(s)
statement(s)
53
Examples
int sum =0;
for( i=1 ; i < 7 ; i+=2 )
sum = sum + i;
int fact =1;
for ( n=5;n>1;n--)
fact = fact * n;
?135 7
i
0 1 4
sum
5
1
9
n
fact
54
Example: lecture2e6.c
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees;
double radians;
printf("Degrees to Radians \n");
for (degrees=0; degrees<=360; degrees+=10)
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
}
return 0;
}
55
Exercise
Determine the number of times that each of the following
for loops are executed.
for (k=3; k<=10; k++)
{
statements;
}
 final  initial 
 increment   1
for (count=-2; count<=5; count++)
{
statements;
}
56
Exercise

Write a loop to print Hello 10 times
for (i=1; i<=10; i++)
{
printf(“Hello\n”);
}


Change it to print Hello 20 times
Change it to print the count besides each hello


Hello 1
Hello 2
57
Exercise

Write program to compute the following using a
for loop
10
i
Result = 55
i 1
10
i
Result = 45
i 5
58
Exercise
Convert the following for loop to while loop
for (i=5; i<10; i++)
{
printf(“ i = %d \n”, i);
}
i=5;
while (i<10)
{
printf(“ i = %d \n”, i);
i++;
}
59
Exercise

Write a loop to compute xy for y integer
without using pow(x,y)
res=1;
for (i=1; i<=y; i++)
{
res = res * x;
20
21
22
23
=1
=2
= 2*2
= 2*2*2
}
60
Exercise

Write a program to compute the following
m
i
0
1
2
3
4
m
x

x

x

x

x

x



x

i 0
total=0;
for (i=0; i<=m; i++)
total = total + pow(x, i);
total=0; sofarx=1;
for (i=0; i<=m; i++)
{
total = total +sofarx;
sofarx = sofarx * x;
}
61
Exercise

Write a program to compute the following
1 1 1 1 1 1 1
1
ln 2          
1 2 3 4 5 6 7
n
ln2=0;
for (i=1; i<=n; i++)
if ( i % 2 == 0)
ln2 = ln2 - 1.0 / i;
else
ln2 = ln2 + 1.0 / i;
62
Exercise

What is the output of the following
program?
for (i=1; i<=5; i++)
{
for (j=1; j<=4; j++)
printf(“*”);
printf(“\n”);
}

Output
****
****
****
****
****
Available on class webpage: lecture2e7.c
63
Exercise

What is the output of the following
program?
for (i=1; i<=5; i++)
{
for (j=1; j<=i; j++)
printf(“*”);
printf(“\n”);
Output
*
**
***
****
*****
}

Available on class webpage: lecture2e8.c
64
Exercise

Modify the following program to produce
the output.
for (i=A; i<=B; i++)
{
for (j=C; j<=D; j++)
printf(“*”);
printf(“\n”);
}
Output
*****
****
***
**
*
65
Exercise

Write a program using loop statements to
produce the output.
Output
*
**
***
****
*****
for (i=1; i<=5; i++)
{
for (j=1; j<=5-i; j++)
printf(" ");
for (k=1; k<=i; k++)
printf("*");
printf("\n");
}
66
break statement

break;
 terminates loop
 execution continues with the first statement following the
loop
sum = 0;
for (k=1; k<=5; k++)
{
scanf(“%lf”,&x);
if (x > 10.0)
break;
sum +=x;
}
printf(“Sum = %f \n”,sum);

Available on class webpage: lecture2e9.c
67
continue statement

continue;
 forces next iteration of the loop, skipping any remaining
statements in the loop
sum = 0;
for (k=1; k<=5; k++)
{
scanf(“%lf”,&x);
if (x > 10.0)
continue;
sum +=x;
}
printf(“Sum = %f \n”,sum);

Available on class webpage: lecture2e10.c
68
Data Files
69
Data Files




Read input of a program from a file
Write output of a program to a file
Files are stored on disk
Consider the following example
Input
3
1
3
3
1
3
3
1
3
2
3
3
3
1
3
Output
Equilateral
Isosceles
Isosceles
Isosceles
Scalene
70
Data Files
Each data file must have a file pointer

file pointer must be defined



FILE *sensor1;
FILE *balloon;
Read
information
from file
file pointer must be associated with a
specific file using the fopen function


sensor1 = fopen(“sensor1.dat”, “r”);
balloon = fopen(“balloon.dat”, “w”);
Write
information
to a file
71
I/O Statements

Input file - use fscanf instead of scanf


fscanf(sensor1, “%1f %lf”, &t, &motion);
Output file - use fprint instead of printf

fprintf(balloon, “%f %f %f\n”, time,
height, velocity);
72
Reading Data Files

counter controlled loop



First line in file contains count
for loop
end of file controlled loop



When file is created EOF is inserted
while loop
feof(fileptr) > 0 when EOF reached
73
Counter controlled loop

Usually first line in file contains the count
#include <stdio.h>
int main()
{
FILE *scorefile;
int score,count,i;
}
Available on webpage as lecture2e12.c
File
6
56
78
93
24
85
63
scorefile = fopen("scores2.txt","r");
fscanf(scorefile,"%d",&count);
for (i=1; i<=count; i++)
{
fscanf(scorefile,"%d",&score);
printf("%d\n",score);
}
fclose(scorefile)
Available on webpage as scores2.txt
return(0);
74
End of file controlled loop
#include <stdio.h>
Available on webpage as lecture2e11.c
int main()
{
FILE *scorefile;
int score;
scorefile = fopen("scores.txt","r");
File
56
78
93
24
85
63
while (feof(scorefile) <= 0)
{
fscanf(scorefile,"%d",&score);
printf("%d\n",score);
}
Available on webpage as scores.txt
fclose(scorefile);
return(0);
}
75
Exercise


Given a file of integers. Write a program that finds the minimum
number in a file.
// algorithm to find minimum in a file
open file
set minimum to a large value
while (there are items to read)
read next number x from file
if (x < min)
min = x
display the minimum
close file
File
56
78
93
24
85
63
Solution available on webpage as lectrue2e13.c
76
Exercise


Given a file of integers. Write a program that searches for
whether a number appears in the file or not.
// algorithm to check for y in a file
open file
set found to false
while (there are items to read and found is false)
read next number x from file
if (x equals y)
set found to true
Display found message to user
Display not found message to user
close file
File
56
78
93
24
85
63
Solution available on webpage as lecture2e14.c
77
Exercise

Read from one file and write to another
FILE *scorefile;
FILE *outfile;
int score;
scorefile = fopen("scores.txt","r");
outfile = fopen("newscores.txt","w");
while (feof(scorefile) <= 0)
{
fscanf(scorefile,"%d",&score);
fprintf(outfile,"%d\n",score);
}
Solution available on webpage as lecture2e15.c
78
Exercise

Write a program that reads a number n
from user and prints all the numbers 1
to n to file “numbers.txt”.
1
2
3
4
5
6
7
1
2
3
4
5
n= 4
n= 7
79