15/09/17
Decisions with Variables
• Need for taking logical decisions during
problem solving
– If (b2 – 4ac) is negative, we should report that the
CS1100 quadratic has no real roots
Introduction to Programming • The if-else programming construct provides the
facility to make logical decisions
Selection Statements • Syntax: if (condition)
Madhu Mutyam
Department of Computer Science and Engineering
{evaluate this part if true}
Indian Institute of Technology Madras else
Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1
{evaluate this part if false}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 2
Conditions Completing the program
• Specified using relational and equality operators if (discrim < 0)
• Relational: >, <, >=, <= {
• Equality: ==, != printf(“no real roots, only complex\n”);
• Usage: for a, b values or variables exit (1);
Terminates execution and
a > b, a < b, a >= b, a <= b, a == b, a != b } returns argument (1)
• A condition is satisfied or true, if the relational else
operator, or equality is satisfied {
• For a = 3 and b = 5: root1 = (−coeff2 + sqrt(discrim))/denom;
– a < b, a <= b, and a != b are true root2 = (−coeff2 − sqrt(discrim))/denom;
– a > b, a >= b, a == b are false
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 3 SD, PSK, NSN, DK, TAG – CS&E, IIT M 4
Statements Assignment statement
Statement: a logical unit of instruction/command General Form:
Program : declarations and one or more statements variable “ = ” expression | constant “;”
assignment statement The declared type of the variable should match the
selection statement type of the result of expression/constant
repetitive statements Multiple Assignment:
function calls etc. var1 = var2 = var3 = expression;
All statements are terminated by semicolon ( ; ) var1 = (var2 = (var3 = expression));
Note: In C, semi-colon is a statement terminator Assignment operator associates right-to-left.
rather than a separator!
SD, PSK, NSN, DK, TAG – CS&E, IIT M 5 SD, PSK, NSN, DK, TAG – CS&E, IIT M 6
1
15/09/17
Compound Statements An Example
• A group of declarations and statements collected {
into a single logical unit surrounded by braces int i, j, k;
– a block or a compound statement This i and k and the previously
i = 1; j = 2; k = 3; declared i and k are different.
• “scope” of the variable declarations if ( expr ) { Not a good programming style.
– part of the program where they are applicable
int i, k;
– the compound statement
• variables come into existence just after declaration i = j;
• continue to exist till end of the block printf(“i = %d\n”, i); // output is 2
• unrelated to variables of the same name outside the block
• block-structured fashion } Note: No semicolon after }
printf(“i = %d\n”, i); // output is 1
} A compound statement can appear wherever a
7 single statement may appear 8
SD, PSK, NSN, DK, TAG – CS&E, IIT M SD, PSK, NSN, DK, TAG – CS&E, IIT M
Selection Statements If Statement
Three forms: if (<expression>) <stmt1> [ else <stmt2>]
single selection: no then reserved Semantics: optional
word
if ( att < 85 ) grade = “W”; expression evaluates to “true”
double selection: – stmt1 will be executed
if (marks < 40 ) passed = 0; /* false = 0 */ expression evaluates to “false”
else passed = 1; /* true = 1 */ – stmt2 will be executed
multiple selection: Else part is optional
switch statement - to be discussed later expression is “true” -- stmt1 is executed
Otherwise the if statement has no effect
SD, PSK, NSN, DK, TAG – CS&E, IIT M 9 SD, PSK, NSN, DK, TAG – CS&E, IIT M 10
Sequence and Selection Flowcharts Grading Example
Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A
int marks;
true
If structure
char grade; Note the semicolon
false
… before else !
Single Entry
Single Exit if (marks <= 50) grade = ‘D’;
false true else if (marks <= 59) grade = ‘C’;
else if (marks <=75) grade = ‘B’;
if - else structure else grade = ‘A’; Unless braces are used, an else part
Sequence goes with the nearest else-less if stmt
Structure …
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11 SD, PSK, NSN, DK, TAG – CS&E, IIT M 12
2
15/09/17
Caution in use of “else” Switch Statement
if ( marks > 40) /* WRONG */ • A multi-way decision statement
if ( marks > 75 ) printf(“you got distinction”); • Syntax:
else printf(“Sorry you must repeat the course”); switch ( expression ) {
case const-expr : statements;
if ( marks > 40) { /*RIGHT*/ case const-expr : statements;
if ( marks > 75 ) printf(“you got distinction”); …
} [default: statements;]
else printf(“Sorry you must repeat the course”); }
SD, PSK, NSN, DK, TAG – CS&E, IIT M 13 SD, PSK, NSN, DK, TAG – CS&E, IIT M 14
Counting Evens and Odds Fall Through
int num, eCount = 0, oCount = 0; • Switch statement:
Counts the number of
scanf (“%d”, &num); even and odd integers in – Execution starts at the matching case and falls through
while (num >= 0) { the input. Terminated by the following case statements unless prevented
switch (num%2) {
giving a negative number explicitly by break statement
case 0: eCount++; break; – Useful for specifying one action for several cases
case 1: oCount++; break; • Break statement:
} – Control passes to the first statement after switch
scanf (“%d”, &num); – A feature requiring exercise of caution
}
printf( “Even: %d , Odd: %d\n”, eCount, oCount);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 15 SD, PSK, NSN, DK, TAG – CS&E, IIT M 16
Switch Statement Flowchart Conditional Operator ( ?: )
Single Entry
Single Exit
• Syntax
case a
true
case a action(s) break
(<expression>)? <stmt1>:<stmt2>
false • Closely related to the if – else statement
case b
true
case b action(s) break if (<expression>) <stmt1> else <stat2>
false • Only ternary operator in C
• E.g.:
case z
true
case z action(s) break (marks < 40)? passed = 0 : passed = 1;
false printf (“ passed = %d\n ”, (marks<40)?0:1);
default action(s)
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17 SD, PSK, NSN, DK, TAG – CS&E, IIT M 18
3
15/09/17
Programming Problems Repetitive Statements
• Write a program to check if a given number is • A very important type of statement
prime. – iterating or repeating a set of operations
• Write a program to count the number of digits in – a very common requirement in algorithms
a given number. Your answer should contain two • C offers three iterative constructs
parts, number of digits before and after the – the while … construct
decimal. (Can you do this only with assignments – the for construct
to variables, and decisions?) – the do … while construct
SD, PSK, NSN, DK, TAG – CS&E, IIT M 19 SD, PSK, NSN, DK, TAG – CS&E, IIT M 20
The while Construct Computing 2n, n>=0, using while Construct
• General form: • Syntax – while (condition){ statement}
while ( <expr> ) <statement> #include<stdio.h>
• Semantics: main( )
– repeat: Evaluate the “expr” true {
expr body
If the “expr” is true int n, counter, value;
execute the “statement” false
printf (“Enter value for n:”);
else
scanf (“%d”, &n);
exit the loop
value = 1;
• “expr” must be modified in the loop or we have
an infinite loop! printf (“current value is %d \n”, value);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 21 SD, PSK, NSN, DK, TAG – CS&E, IIT M 22
Contd… Testing the Program
counter = 0; • Choose test cases:
while (counter <= n) – A few normal values: n = 2, 5, 8, 11
{ – Boundary values: n = 0, 1
– Invalid values: n = –1
value = 2 * value;
• Hand simulate the execution of the program
printf (“current value is %d \n”, value);
– On paper, draw a box for each variable and fill in the
counter = counter + 1; initial values (if any)
} Exercise: try this – Simulate exec. of the program one statement at a time
program and
} identify problems – For any assignment, write the new value of the
variable in the LHS
SD, PSK, NSN, DK, TAG – CS&E, IIT M 23
– Check if the output is as expected in each test case 24
SD, PSK, NSN, DK, TAG – CS&E, IIT M
4
15/09/17
Hand Simulation Contd…
n counter value condition n counter value
#include<stdio.h> counter = 0;
4 1 TF 4 14
50
2
3 16
32
18
2
4
main( ) while (counter <= n)
Current value is 1 Current value is 1
{ {
int n, counter, value; value = 2 * value;
printf (“Enter value for n:”); printf (“current value is %d \n”, value);
scanf (“%d”, &n); counter = counter + 1; Current value is 2
value = 1; } Current value is 4
Current value is 8
printf (“current value is %d \n”, }
Current value is 16
value);
Current value is 32
SD, PSK, NSN, DK, TAG – CS&E, IIT M 25 SD, PSK, NSN, DK, TAG – CS&E, IIT M 26
More on Loops Reversing a Number: Methodology
• Loop execution can be controlled in two ways: • Print the reverse of a given integer:
counter-controlled and sentinel-controlled. • E.g.: 234 à 432
• Counter – loop runs till counter reaches its limit. • Method: Till the number becomes zero,
– Use it when the number of repetitions is known. – extract the last digit
• Sentinel – loop runs till a certain condition is – number modulo 10
encountered. – make it the next digit of the result
– For example – a \n (newline) is read from the input. – multiply the current result by 10 and
– Use it when the number of repetitions is a property of – add the new digit
the input and not of the problem being solved.
SD, PSK, NSN, DK, TAG – CS&E, IIT M 27 SD, PSK, NSN, DK, TAG – CS&E, IIT M 28
Reversing a Number: Illustration Reversing a Number: Program
• x is the given number main( ){
• y is the number being computed int x = 0, y = 0;
• x = 56342 y = 0 printf ("input an integer :\n");
• x = 5634 y= 0*10 + 2 = 2 scanf ("%d", &x);
• x = 563 y= 2*10 + 4 = 24 while (x > 0){ Remember integer division
truncates the quotient
• x = 56 y = 24*10 + 3 = 243 y = y*10 + ( x % 10 );
• x=5 y = 243*10 + 6 = 2436 x = (x / 10);
• x=0 y = 2436*10 + 5 = 24365 }
Termnation condition: Stop
printf ("The reversed number is %d \n", y);
x = x/10 when x becomes zero y = y*10 + (x%10)
SD, PSK, NSN, DK, TAG – CS&E, IIT M 29
} PSK, NSN, DK, TAG – CS&E, IIT M
SD, 30
5
15/09/17
Perfect Number Detection
main ( ){ Perfect number: sum of proper
divisors adds up to the number
int d=2, n, sum=1;
d<n will also do, but would
scanf (“%d”, &n); do unnecessary work
while (d <= (n/2)) {
if (n%d == 0)
sum += d;
d++;
}
if (sum == n) printf (“%d is perfect\n”, n);
else printf (“%d is not perfect\n”, n);
Exercise: Modify to find
} PSK, NSN, DK, TAG – CS&E, IIT M
SD, 31
the first n perfect numbers