Вы находитесь на странице: 1из 42

Week 3

Dry-Run Type Casting Conditional Statements

Dry -Run
How does the programmer know whether his/her program is correct? S/He should be able to anticipate the results. What if the results are wrong? How does s/he know which lines are wrong? He should be able to anticipate what is happening at different lines and then check with what the computer is actually giving. The programmer should thus dry-run his program.
When a program executes, there is processing of data values. These cause the values of variables to change. During a dry-run the programmer should be able to follow all the changes in data values.

Trace Tables (1)


When performing a dry-run, a useful tool is the trace-table. In the trace-table the programmer writes the values of each variable at chosen line-numbers as shown below, for the given program.

Eg. - Consider the following program 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. #include <stdio.h> int main() { int x,y,z; x=15; y=2*x+5; z=x+y; y = z + 2*y; x = 2*x; y= 2*x + y; z = z + y; printf (The final values are %d %d %d\n,x,y,z); return 1; }

Trace Tables (2)

Line No. 5 6 7 8 9 10 11

x 15 15 15 15 30 30 30

y ? 35 35 120 120 180 180

z ? ? 50 50 50 50 230

Trace Tables (3)


Determine the trace table of the following program. 1. #include <stdio.h> 2. int main() 3. { 4. int a,b,c; 5. b = 20; 6. a = b+10; 7. c = 2*a; 8. b = 2*c + 10; 9. a = c - 15; 10. b = b + 1; 11. c = a + b; 12. printf(The final values are %d %d %d \n, a, b, c); 13. return 1; 14. }

Trace Tables (4)

Line No. 4 5 6 7 8 9 10

a ? 30 30 30 45 45 45

b 20 20 20 130 130 131 131

c ? ? 60 60 60 60 176

Type Casting
C type casting is used to tell the C compiler to treat a variable as of a different type in a specific context. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to a float. Casting allows you to make this type conversion explicit, or to force it when it wouldnt normally happen.
7

Type Casting
To perform explicit type casting, put the desired type including modifiers (like unsigned) inside parentheses to the left of the variable or constant you want to cast.
Eg. Y= (float) x; Z = (float) x / y; Casting is particularly useful when we want to divide an integer x by another integer y, and we want the result to include the fractional part. With the declarations
float z; int x,y;

given that the values of x and y are respectively 12 and 5; z = x/y will yield 2 as the value of z, whereas z = (float) x/ y will yield 2.4.

Type Casting
/*Explicit casting from int to char*/
Another equivalent code: int x; X=97; printf(%c , (char)x);

/*Implicit casting from int to char thanks to %c*/


A last equivalent code: int x; X=97; printf(%c , x);

Consider the code:


char c1=97,c2=98,c3=99; printf(%c %c %c , c1,c2,c3); This code prints: abc since 97 is the ASCII code of a, 98 is the ASCII code of b and 99 is the ASCII code of c.

Relational and Logical Operators


Relational operators ( ==, !=, >, <, >=, <= ) The result of a relational operation is Boolean (true or false) == Equal != Different > Greater than < Less than >= Greater or equal than <= Less or equal than Logical operators ( !, &&, || ) ! Has one operand to its right and it only inverts the value of the operand . For example, !(5= = 5) returns false. && and || correspond to boolean logic operations AND and OR respectively.

Conditional Statements
In the programs discussed so far all statements are executed once and only once.
This is unrealistic in practice.

In practice programs also contain


statements that are executed depending on certain conditions being satisfied and statements that are executed several times

For such statements, we need control structures

11

SELECTION (IF STATEMENTS)


The if (selection) statements allows branching (decision making) depending upon the value or state of variables. This allows statements to
be executed or skipped, depending upon decisions. The basic format is, if( expression ) program statement; Example
#include <stdio.h> int main() { int x; printf("Input x:"); scanf("%d",&x); if ( x < 65 ) printf("Low Value"); return 1; }
12

SELECTION (IF STATEMENTS)


In the above example, the words Low Value are displayed only if the value of the integer variable x is less than 65. Two types of if statements: simple alternative if compound alternative if...else Example;
#include <stdio.h> int main() { int x; printf("Input x: "); scanf("%d",&x); if ( x < 65 ) printf("Low Value"); else printf("High Value"); return 1; }
13

Single Alternative Decision


An action is taken if the condition is true, otherwise the control goes to the next statement. Syntax if (condition) statement If condition is true, statement is executed; otherwise statement is skipped.

14

condition

{ }
Variable or literal or expression Eg. of conditions (x > y) (x<=z) (y==5) (z!=0) ((x+y) <10)) Conditions evaluate to true or false

Relational Operator

{ }
Variable or literal or expression
15

Relational Operators : <, >, <=, >=, ==,!=

Exercise - A company pays a bonus equivalent to half the monthly


salary to its employees. Those who have worked for the company for 10 years or more obtain an addtional bonus of Rs 3000. Write a program to input an employees salary and number of years of service and output the total bonus obtainable. Pseudocode Design Input Salary Input Years-of-service bonus = 0.5xsalary if (year-of-service >=10) Add 3000 to bonus Output bonus

16

#include <stdio.h> int main() { float salary, bonus; int years; printf("Input Salary: "); scanf("%f", &salary); printf("Input No. of years of service: "); scanf("%d", &years); bonus = 0.5*salary; if (years>=10) bonus = bonus +3000; printf("Total Bonus is %.2f\n", bonus); }

17

The Compound Statement(1)


Exercise - A company pays a travel grant of Rs 5000 and a child
allowance of Rs 3000 per child to all its employees earning above Rs 25,000. Write a program to input all required information for an employee and display the total income obtainable. Pseudo codes
input Salary income = salary if (income > 25000) travel-grant=5000 input no-of-children child-allow = no-of-children x 3000 income= income+travel-grant + child-allow endif output income
18

The Compound Statement(2)


#include <stdio.h> int main() { float salary, income,travel_grant,child_allow; int children; printf("Input Salary: "); scanf("%f", &salary); income= salary; if (salary>25000) { travel_grant=5000; printf("Input No. of children: "); scanf("%d",&children); child_allow=children*3000; income = income + travel_grant + child_allow; } printf("Total income is %.2f",income); return 1; }
19

The Compound Statement(3)


Syntax if (condition) { statement; . statement; }

20

Pitfalls
Using = in place of == What is the difference between these two? if (toss = = 7) printf(You win the bet.); if (toss = 7) printf(You win the bet.);

21

Double Alternative Decision (1)


An action (or set of actions) is taken if the condition is true, another action (or set of actions) is taken if the condition is false, then the control goes to the next statement.
if ... else is the typical double alternative.

22

Double Alternative Decision (2)


Exercise - A company pays an end-of-year bonus to its
employees. For those employees who have worked for the company for 10 years or more the bonus is equal to their monthly salary whereas for others it is half the monthly salary. Write a program to input an employees salary and number of years of service and output the bonus obtainable.
Pseudocode input salary input years-of-service if (years-of-service >=10) bonus = salary else bonus = 0.5* salary output bonus
23

#include <stdio.h> int main() { float salary, bonus; int years; printf("Input Salary: "); scanf("%f", &salary); printf("Input No. of years of service: "); scanf("%d", &years); if (years>=10) bonus = salary; else bonus = 0.5*salary; printf(" Bonus is %.2f\n", bonus); return 1; }
24

The if-else Statement


Syntax if (condition) statement1 else statement2 If condition is true then statement1 is executed and statement2 is skipped. If condition is false statement1 is skipped and statement2 is executed.

25

if ... else Statement


Syntax
if (condition) {statement 1; statement 2; . statement m;} else { statement m+1; statement m+2; .. statement n;} If condition is true then statement1 statement m are executed and statement m+1 to statement n are skipped. If condition is false statement 1 .. statement m are skipped and statement m+1 to statement n are executed.
26

if .else examples
Exercise - A company pays a travel grant of Rs 5000 and a
children allowance of Rs 3000 per child to all its employees earning above Rs 25,000, whereas other employees receive a travelling allowance of Rs 3000 and a children allowance of Rs 2500 per child. Write a program to input all required information for an employee and display the total income obtainable.

27

Pseudo codes
input Salary input no-of-children if (income > 25000) travel-grant=5000 child-allow = no-of-children x 3000 else travel-grant=3000 child-allow = no-of-children x 2500 endif income= salary+travel-grant + child-allow output income

28

#include <stdio.h> int main() { float salary, income,travel_grant,child_allow; int children; printf("Input Salary: "); scanf("%f",&salary); printf("Input No. of children: "); scanf("%d", &children); if (salary>25000) { travel_grant=5000; child_allow=children*3000; }

else { travel_grant=3000; child_allow=children*2500; } income = salary+ travel_grant + child_allow; printf("Total income is %.2f\n",income); return 1; }

29

Nested if Statements
A conditional structure can be enclosed in another conditional structure if (condition 1) { statements; if (condition 2); { statements; } statements; } . ..
30

Exercise
Students taking a given module are given chocolates according to the marks they obtain in the exams and their gender. Female students obtain a weight of chocolate (in grams) equivalent to 1.5 times their marks if they score 50 and above. Otherwise they obtain a weight equivalent to their marks. Male students obtain an amount equivalent to 1.25 times their marks irrespective of the marks. Write a program to input the marks of a student and the gender and output the weight of chocolate that he/she should obtain.

31

#include <stdio.h> int main() { float marks, weight ; char gender;

if (gender == 'f') if (marks >= 50) weight=1.5 *marks; else weight= marks; printf("Marks? "); else scanf("%f",&marks); weight = 1.25* marks; printf("Gender: (m/f): "); printf("Weight of Chocolate scanf("%c",&gender); obtained is %.2f\n",weight); getchar(); return 1; }
32

The Switch Statement


The switch statement allows you to rewrite code which uses a lot of if.else statements, making the program logic much easier to read. It can be used only when we have a condition of type (expression = = literal) or (variable = = literal)

33

Eg. consider a program that reads an integer value from 0 to 5 and outputs the value in words.
#include <stdio.h> int main() { int value ; printf("Enter value: "); scanf("%d",&value); if (value == 0) printf("zero"); else if (value == 1) printf("one\n"); else if (value == 2) printf("two\n"); else if (value == 3) printf("three\n"); else if (value == 4) printf("four\n"); else if (value == 5) printf("five\n"); else printf("Wrong value\n"); return 1; }

34

Using Switch

#include <stdio.h> int main() { int value ; printf("Enter value: "); scanf("%d",&value); switch (value) { case 0: { printf("zero"); break;} case 1: { printf("one\n"); break; } case 2: { printf("two\n"); break; }

case 3: { printf("three\n"); break; } case 4: { printf("four\n"); break; } case 5: { printf("five\n"); break; } default: { printf("Wrong value\n"); break; } } return 1; }
35

Exercise: A bank has 4 types of accounts with annual interest rates as follows:
Savings 8% Savings with Cheque Book 5% Current 4% Fixed deposits 10%

Write a program that allows the input of the current balance of an account and the type of account and displays the total interest obtainable. Make use of the switch statement. Note : You have to choose the type of input you wish to use for account type.

36

#include <stdio.h> int main() { int account_type ; float balance, interest; printf("balance:"); scanf("%f",&balance); printf("Choose an Account Type\n"); printf("1: Savings \n"); printf("2: Savings with Cheque Book \n"); printf("3: Current \n"); printf("4: Fixed Deposits\n"); printf("Input account type: "); scanf("%d",&account_type);

switch (account_type) { case 1: {interest=0.08*balance; break;} case 2: {interest=0.05*balance; break;} case 3: {interest=0.04*balance; break;} case 4: {interest=0.1*balance; break;} default: { interest=-1; break;} } balance=balance+interest; if(interest==-1) printf("wrong type"); else printf("balance is %7.2f", balance); return 1; }

37

Compound Conditions (1)


Conditions can be combined (or compounded) by the logical operators AND OR NOT AND:
Compound Condition
condition 1 condition 2 True True False False True False True False (Condition 1 and Condition 2) True False False False
38

Compound Conditions (2)


OR : condition 1 condition 2 True True True False False True False Fal NOT: Compound Condition condition 1 True False (NOT condition1) False True
39

Compound Condition (condition 1 OR condition 2) True True True False

Compound Conditions (3)


In C/C++, AND is written as && OR as || NOT as ! Eg. if ((x ==10) && (y>5)) if ((x< 5) || (y <7)) if (!(x==0))

40

Exercise - A company pays a travel grant of Rs 5000 and a


children allowance of Rs 3000 per child to all its employees aged 40 or above and earning above Rs 25,000, whereas other employees receive a travelling allowance of Rs 3000 and a flat children allowance of Rs 2500, provided the employee has at least one child. Write a program to input all required information for an employee and display the total income obtainable.

41

Pseudo codes
input Salary input no-of-children input age child-allow=0 if (income > 25000) and (age>=40) travel-grant=5000 child-allow = no-of-children x 3000 else travel-grant=3000 if (no-of-children >= 1) child-allow = 2500 endif endif income= salary+travel-grant + child-allow output income

42

Вам также может понравиться