0% found this document useful (0 votes)
10 views

Lecture 7 Control

Uploaded by

aranya13078
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 7 Control

Uploaded by

aranya13078
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Introduction to Control Statements

Increment & Decrement (section 2.5)


 j=i++;
 First current value of i is assigned to j
 Then i is incremented
 If the current value of i is 5
 After the execution of the statement the value of
 i: 6
 j: 5
if statement

true
num>=0 num is positive

false
if statement
 Selection statement/conditional statement
 Operation governed by outcome of a conditional test
 if(expression) statement;
 expression:
 any valid C expression
 If expression is true statement will be executed
 If expression is false statement will be bypassed
 true: any nonzero value
 false: zero
 if(num+1) printf(“nonzero");//num!=-1 statement will execute
 Normally expression consists of relational & logical operator
if statement
#include<stdio.h>
int main(void)
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");//if(num>-1)
if(num<0) printf("num is negative");
return 0;
}
if statement
 Common programming error:
 Placing ; (semicolon) immediately after condition in if
 if(expression); statement;
 Confusing equality operator (==) with assignment operator (=)
 if(a=b)
 if(a=5)
 if(9=5)
 left operand must be l-value
 if(9+5)
if-else statement
 if(expression) statement1;
else statement2;
 If expression is true statement1 will be evaluated and statement1 2
will be skipped
 If expression is false statement1 will be bypassed and statement2
will be executed
 Under no circumstances both the statements will execute
 Two-way decision path
if-else statement
#include<stdio.h>
int main(void)
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");//if(num>-1)
else printf("num is negative");
return 0;
}
if-else statement
 else part is optional
 The else is associated with closest else-less if
 if(n>0)
if(a>b) z=a;
else z=b;
 Where else will be associated is shown by indentation
 Braces must be used to force association with the first
 if(n>0)
{
if(a>b) z=a;
}
else z=b;
Nested if (section 3.4)
#include<stdio.h> else
int main(void) {
{ if(id<61)
int id; printf("B1\n");
printf("Please enter last else
3 digits of your id:\n"); printf("B2\n");
scanf("%d", &id); }
printf("You are in "); return 0;
if(id%2) }
{
if(id<60)
printf("A1\n");
else
printf("A2\n");
}
blocks of code
 Surround the statements in a block with opening and
ending curly braces.
 One indivisible logical unit
 Can be used anywhere a single statement may
 Multiple statements
 Common programming error:
 Forgetting braces of compound statements/blocks
blocks of code
 if(expression) {
statement1;
statement2;

statementN;
}
else {
statement1;
statement2;

statementN;
}
 If expression is true all the statements with if will be executed
 If expression is false all the statements with else will be executed
Example
#include<stdio.h> else
int main( ) {
{ int a, b, c;
int numOfArg, sum; scanf("%d %d %d", &a,
&b, &c);
scanf("%d", &numOfArg);
sum=a+b+c;
if(numOfArg==2)
}
{
printf("The sum is %d\n",
int a, b;
sum);
scanf("%d %d", &a, &b);
return 0;
sum=a+b;
}
}
if-else if statement
 if(expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
if-else if statement
 Multi-way decision
 expressions are evaluated in order
 If any expression is true
 the statement associated with it is executed
 Multiple statements can be associated using curly braces
 the whole chain is terminated
 If none of the expressions are true
 else part is executed
 Handles none of the above/ default case
 Optional
if-else if statement
#include<stdio.h> …
int main( ) …
{ …
int num; else
scanf("%d", &num); printf("Fail");
if(num>=80) return 0;
printf("A+\n"); }
else if(num>=75)
printf("A\n");
else if(num>=70)
printf("A-\n");
if-else if statement
#include<stdio.h> else if(numOfArg==3)
int main( ) {
{ int a, b, c;
int numOfArg, sum; scanf("%d %d %d", &a, &b,
scanf("%d", &numOfArg); &c);
if(numOfArg==2) sum=a+b+c;
{ }
int a, b; printf("The sum is %d\n",
sum);
scanf("%d %d", &a,
&b); return 0;
sum=a+b; }
}
Short Circuit Evaluation
if(a!=0 && num/a)
{
}
Conditional Expressions
 Uses ternary operator “?:”
 expression1?expression2:expression3;
 z= (a>b)? a: b; /* z=max(a,b);*/
 Can be used anywhere an expression can be
Example
 Find maximum of three numbers
 Find second maximum of three numbers
 Find minimum of four numbers
switch case
switch (expression) {
case constant: statements
case constant: statements
default: statements
}
 Use of break
switch case
switch (month) {
case 1: printf("January\n");
case 2: printf("February\n");


default: printf("Invalid\n");
}
switch case
#include<stdio.h>
#include<conio.h>
int main()
{
char i=getche();//getch();
switch (i) {
case '0': case '1': case '2': case ‘3': case ‘4':
case ‘5': case ‘6': case ‘7': case ‘8': case '9':
printf(" : digit\n");
break;
default: printf(" : non digit\n");}
return 0;
}
 Use of break
switch case
//int x=a/b;
int x, a, b;
scanf("%d %d", &a, &b);
switch (b) {
case 0:
printf("divide by zero error\n");
break;
default: x=a/b;
}
for loop
 Allows one or more statements to be repeated
 for(initialization; conditional-test; increment) statement;
 Most flexible loop
for loop
 for(initialization; conditional-test; increment) statement;
 initialization:
 Give an initial value to the variable that controls the loop
 loop-control variable
 Executed only once
 Before the loop begins
for loop
 for(initialization; conditional-test; increment) statement;
 conditional-test:
 Tests the loop-control variable against a target value
 If true the loop repeats
 statement is executed
 If false the loop stops
 Next line of code following the loop will be executed
for loop
 for(initialization; conditional-test; increment) statement;
 increment:
 Executed at the bottom of the loop
for loop
Single Statement Block of Statements
for(i=1; i<100; i++) sum=0;
printf("%d\n", i); prod=1;
for(i=1; i<5; i++)
 Prints 1 to 99
{
for(i=100; i<100; i++) sum+=i;
printf("%d\n", i); prod*=i;
 This loop will not execute }
printf("sum, prod is
%d, %d\n", sum, prod);
for loop
for(i=1; i<3; i++) Initialization part is executed
printf("%d\n", i); only once

1. i is initialized to 1
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
2. Conditional test i<3 is true as i is 1, so the loop executes
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
3. The value of i will be printed, which is 1
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
3. The value of i will be incremented, so now i is 2.
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
4. Conditional test i<3 is true as i is 2, so the loop executes
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
5. The value of i will be printed, which is 2
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
6. The value of i will be incremented, so now i is 3.
for loop
for(i=1; i<3; i++)
printf("%d\n", i);
7. Conditional test i<3 is false as i is 3, so the loop stops
for loop
 for loop can run negatively
 decrement can be used instead of increment
 for(i=20; i>0; i--) ...
 Can be incremented or decremented by more than one
 for(i=1; i<100; i+=5)
for loop
 All of the following loops will print 1 to 99
 for(i=1; i<100; i++)
printf("%d\n", i);
 for(i=1; i<=99; i++)
printf("%d\n", i);
 for(i=0; i<99; i++)
printf("%d\n", i+1);
 for(i=0; i<=98; i++)
printf("%d\n", i+1);
 So selection of initial value and loop control condition is important
for loop
GCD of two numbers:
#include <stdio.h>
int main(void) {
int a, b, min, i, gcd;
scanf("%d %d", &a, &b);
min=(a<b)?a:b;
for(i=1; i<=min; i++)
if(a%i==0 && b%i==0)
gcd=i;
printf("gcd of %d & %d is %d\n", a, b, gcd);
return 0;
}
for loop
Nth Fibonacci number:
#include <stdio.h> else
int main(void) { {
int n, i, fibn=0, fibn=fibn_1+fibn_2;
fibn_1=1, fibn_2=0; fibn_2=fibn_1;
scanf("%d", &n); fibn_1=fibn;
for(i=0; i<n; i++) }
{
if(n==1) }
fibn=i; printf("%d\n", fibn);
return 0;
}
Nested for loop
#include<stdio.h> Output:

int main()
{ 1, 1
for(int i=1; i<=3; i++) 2, 1
{ 2, 2
for(int j=1; j<=i; j++)
3, 1
{
3, 2
printf("%d, %d\n", i, j);
}
3, 3
}
What if the condition is
return 0; j<=3?
}
Nested for loop
#include<stdio.h> for(int j=0; j<i; j++)//if
j=1?
int main() {
{ prod=prod*i;
}
int n, sum, prod;
sum=sum+prod;
prod=1;
}
sum=0; printf("sum is %d\n", sum);
scanf("%d", &n); return 0;
for(int i=1; i<=n; i++)//if i<n? }
{
prod=1;
Nested for loop
#include<stdio.h> for( ;j<=n; j++)
{
int main() printf("1 ");
{ }
int n, i, j; printf("\n");
scanf("%d", &n); }
for(i=1; i<=n; i++)//row
by row return 0;
{ }
for(j=1; j<=i; j++)
{
printf("0 ");
}
Loop variation
 for( ; ; ){}
 for(ch=getche(); ch!=‘q’; ch=getche()) {}
 for(i=0; i<n; )
{
i++;
}
Homework on loop
 Given a number as input write to program to calculate the number
of digits.
 Given a number as input write to program to calculate the sum of
it’s digits.
 Write a program to find gcd of two given numbers
 Write a program to find xm where x and m are inputs
 Write a program to convert a decimal number to a binary number
 Write a program to expand shorthand notation like a-z

 CT
while loop
 while(expression) statement;
 for(initialization; conditional-test; increment) statement;
 initialization;
while(conditional-test)
{
statement;
increment;
}
while loop
while for
#include<stdio.h> #include<stdio.h>
int main()
{ int main()
int i=0; {
while(i<=9) int i;
{
printf("%d\n", i); for(i=0; i<=9; i++)
i++; printf("%d\n", i);
}
return 0;
return 0;
} }
while loop
 Common error
 Forgetting to increment
 Normally used when increment is not needed
 while(ch!=‘q’)
{

ch=getche();
}
do while loop
 do
statement
while(expression);
 for(initialization; conditional-test; increment) statement;
 initialization;
do
{
statement;
increment;
} while(conditional-test);
do while loop
 Test is at the bottom
 Will execute at least once
 do
{

ch=getche();
} while(ch!=‘q’);
 Common error
 Forgetting the semicolon (;) after while
while loop
do while for
#include<stdio.h> #include<stdio.h>
int main()
{ int main()
int i=0; {
do int i=0;
{
printf("%d\n", i); for(i=1; i<=9; i++)
i++; printf("%d\n", i);
}while(i<=9);
return 0;
return 0;
} }
for loop
/*prime number tester*/ /*test for factors*/
#include<stdio.h> for(i=2; i<=num/2; i++)
int main() if((num%i)==0) is_prime=0;
{ if(is_prime==1)
int i, num, printf("%d is prime\n",
is_prime=1; num);
printf("Enter the else
number to test: "); printf("%d is not
scanf("%d", &num); prime\n", num);
return 0;
}
for loop
/*prime number tester*/ /*test for factors*/
#include<stdio.h> for(i=2; i<=num/2; i++)
int main() if(!(num%i)) is_prime=0;
{ if(is_prime)
int i, num, printf("%d is prime\n",
is_prime=1; num);
printf("Enter the else
number to test: "); printf("%d is not
scanf("%d", &num); prime\n", num);
return 0;
}
while loop
/*prime number tester*/ while(i<=num/2)
#include<stdio.h> {
if(!(num%i)) is_prime=0;
int main()
i++;
{ }
int i, num, if(is_prime)
is_prime=1; printf("%d is prime\n",
printf("Enter the num);
number to test: "); else
scanf("%d", &num); printf("%d is not
prime\n", num);
/*test for factors*/ return 0;
i=2; }
do while loop
/*prime number tester*/ i++;
#include<stdio.h> }while(i<=num/2);
int main() if(is_prime)
{ printf("%d is prime\n",
int i, num, is_prime=1; num);
printf("Enter the number to else
test: "); printf("%d is not
scanf("%d", &num); prime\n", num);
/*test for factors*/ return 0;
i=2; }
do It will show that 2 is not
prime
{
if(!(num%i)) is_prime=0;
Use of break
/*prime number tester*/ /*test for factors*/
#include<stdio.h> for(i=2; i<=num/2; i++)
if(!(num%i))
int main() {
{ is_prime=0;
int i, num, is_prime=1; break;
printf("Enter the number }
to test: "); if(is_prime)
scanf("%d", &num); printf("%d is prime\n",
num);
else
printf("%d is not
prime\n", num);
return 0;
}
Use of continue
#include<stdio.h> Output:

int main() 2, 1
{ 3, 1
for(int i=1; i<=3; i++)
3, 2
{
for(int j=1; j<=i; j++)
{
if(i==j) continue;
printf("%d, %d\n", i, j);
}
}

return 0;
}
Input characters
 getche()/getch()/getchar can be used
 getchar()
 Compiler dependent
 waits for carriage return
 Read only one char
 Other input and carriage return will be in buffer
 Subsequent input (e.g, scanf) will consume them.
 Defined in stdio.h
 getche()/getch()
 Return immediately after a key is pressed
 Defined in conio.h

You might also like